AI Practical 07
AI Practical 07
row = 0
column = 0
# iterate over rows of board
while True:
# place queen in next row
while column < size:
if board.is_this_column_safe_in_next_row(column):
board.place_in_next_row(column)
row += 1
column = 0
break
else:
column += 1
else:
flag = False
Prac4
4a. Write a program to implement A* algorithm.
from simpleai.search import SearchProblem, astar
problem = HelloProblem(initial_state='')
result = astar(problem)
print(result.state)
print(result.path())
Prac5
5a. Write a program to solve water jug problem.
# 3 water jugs capacity -> (x,y,z) where x>y>z
# initial state (12,0,0)
# final state (6,6,0)
capacity = (12,8,5)
# Maximum capacities of 3 jugs -> x,y,z
x = capacity[0]
y = capacity[1]
z = capacity[2]
# to mark visited states
memory = {}
# store solution path
ans = []
def get_all_states(state):
# Let the 3 jugs be called a,b,c
a = state[0]
b = state[1]
c = state[2]
if(a==6 and b==6):
ans.append(state)
return True
# if current state is already visited earlier
if((a,b,c) in memory):
return False
memory[(a,b,c)] = 1
#empty jug a
if(a>0):
#empty a into b
if(a+b<=y):
if( get_all_states((0,a+b,c)) ):
ans.append(state)
return True
else:
if( get_all_states((a-(y-b), y, c)) ):
ans.append(state)
return True
#empty a into c
if(a+c<=z):
if( get_all_states((0,b,a+c)) ):
ans.append(state)
return True
else:
if( get_all_states((a-(z-c), b, z)) ):
ans.append(state)
return True
#empty jug b
if(b>0):
#empty b into a
if(a+b<=x):
if( get_all_states((a+b, 0, c)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b-(x-a), c)) ):
ans.append(state)
return True
#empty b into c
if(b+c<=z):
if( get_all_states((a, 0, b+c)) ):
ans.append(state)
return True
else:
if( get_all_states((a, b-(z-c), z)) ):
ans.append(state)
return True
#empty jug c
if(c>0):
#empty c into a
if(a+c<=x):
if( get_all_states((a+c, b, 0)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b, c-(x-a))) ):
ans.append(state)
return True
#empty c into b
if(b+c<=y):
if( get_all_states((a, b+c, 0)) ):
ans.append(state)
return True
else:
if( get_all_states((a, y, c-(y-b))) ):
ans.append(state)
return True
return False
initial_state = (12,0,0)
print("Starting work...\n")
get_all_states(initial_state)
ans.reverse()
for i in ans:
print(i)
5b. Design the simulation of TIC – TAC –TOE game using min-max
algorithm.
import os
import time
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player = 1
########win Flags##########
Win = 1
Draw = -1
Running = 0
Stop = 1
###########################
Game = Running
Mark = 'X'
def DrawBoard():
print("___|___|___")
print("___|___|___")
print(" | | ")
def CheckPosition(x):
return True
else:
return False
def CheckWin():
global Game
Game = Win
Game = Win
Game = Win
Game = Win
Game=Win
Game = Win
Game=Win
elif(board[1]!=' ' and board[2]!=' ' and board[3]!=' ' and board[4]!=' ' and
board[5]!=' ' and board[6]!=' ' and board[7]!=' ' and board[8]!=' ' and board[9]!=' '):
Game=Draw
else:
Game=Running
print("Tic-Tac-Toe Game")
print()
print()
print("Please Wait...")
time.sleep(1)
while(Game == Running):
os.system('cls')
DrawBoard()
if(player % 2 != 0):
Mark = 'X'
else:
Mark = 'O'
choice = int(input("Enter the position between [1-9] where you want to mark :"))
if(CheckPosition(choice)):
board[choice] = Mark
player+=1
CheckWin()
os.system('cls')
DrawBoard()
if(Game==Draw):
print("Game Draw")
elif(Game==Win):
player-=1
if(player%2!=0):
print("Player 1 Won")
else:
print("Player 2 Won")
Prac6
6a. Write a program to solve Missionaries and Cannibals problem.
import math
# Missionaries and Cannibals Problem
class State():
def __init__(self, cannibalLeft, missionaryLeft, boat, cannibalRight,missionaryRight):
self.cannibalLeft = cannibalLeft
self.missionaryLeft = missionaryLeft
self.boat = boat
self.cannibalRight = cannibalRight
self.missionaryRight = missionaryRight
self.parent = None
def is_goal(self):
if self.cannibalLeft == 0 and self.missionaryLeft == 0:
return True
else:
return False
def is_valid(self):
if self.missionaryLeft >= 0 and self.missionaryRight >= 0 \
and self.cannibalLeft >= 0 and self.cannibalRight >= 0 \
and (self.missionaryLeft == 0 or self.missionaryLeft >=
self.cannibalLeft) \
and (self.missionaryRight == 0 or self.missionaryRight >=self.cannibalRight):
return True
else:
return False
def __hash__(self):
return hash((self.cannibalLeft, self.missionaryLeft, self.boat, self.cannibalRight,
self.missionaryRight))
def successors(cur_state):
children = [];
if cur_state.boat == 'left':
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft -2, 'right',
cur_state.cannibalRight, cur_state.missionaryRight + 2)
def breadth_first_search():
initial_state = State(3,3,'left',0,0)
if initial_state.is_goal():
return initial_state
frontier = list()
explored = set()
frontier.append(initial_state)
while frontier:
state = frontier.pop(0)
if state.is_goal():
return state
explored.add(state)
children = successors(state)
for child in children:
if (child not in explored) or (child not in frontier):
frontier.append(child)
return None
def print_solution(solution):
path = []
path.append(solution)
parent = solution.parent
while parent:
path.append(parent)
parent = parent.parent
for t in range(len(path)):
state = path[len(path) - t - 1]
print ("(" + str(state.cannibalLeft) + "," + str(state.missionaryLeft) \
+ "," + state.boat + "," + str(state.cannibalRight) + "," + \
str(state.missionaryRight) + ")")
def main():
solution = breadth_first_search()
print ("Missionaries and Cannibals solution:")
print ("(cannibalLeft,missionaryLeft,boat,cannibalRight,missionaryRight)")
print_solution(solution)
GOAL = '''1-2-3
4-5-6
7-8-e'''
INITIAL = '''4-1-2
7-e-3
8-5-6'''
def list_to_string(list_):
def string_to_list(string_):
if element == element_to_find:
return ir, ic
# we create a cache for the goal position of each piece, so we don't have to
goal_positions = {}
rows_goal = string_to_list(GOAL)
class EigthPuzzleProblem(SearchProblem):
rows = string_to_list(state)
actions = []
if row_e > 0:
actions.append(rows[row_e - 1][col_e])
if row_e < 2:
actions.append(rows[row_e + 1][col_e])
if col_e > 0:
actions.append(rows[row_e][col_e - 1])
if col_e < 2:
actions.append(rows[row_e][col_e + 1])
return actions
'''Return the resulting state after moving a piece to the empty space.
'''
rows = string_to_list(state)
rows[row_e][col_e]
return list_to_string(rows)
but needed.
'''
return 1
'''
rows = string_to_list(state)
distance = 0
return distance
result = astar(EigthPuzzleProblem(INITIAL))
print(state
Prac7
7a. Write a program to shuffle Deck of cards.
#first let's import random procedures since we will be shuffling
import random
#next, let's start building list holders so we can place our cards in there:
cardfaces = []
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
royals = ["J", "Q", "K", "A"]
deck = []
for j in range(4):
constraints = [
print(backtrack(my_problem))
print(backtrack(my_problem,
variable_heuristic=MOST_CONSTRAINED_VARIABLE))
print(backtrack(my_problem,
variable_heuristic=HIGHEST_DEGREE_VARIABLE))
print(backtrack(my_problem,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(backtrack(my_problem,
variable_heuristic=MOST_CONSTRAINED_VARIABLE,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(backtrack(my_problem,
variable_heuristic=HIGHEST_DEGREE_VARIABLE,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(min_conflicts(my_problem))