0% found this document useful (0 votes)
51 views

Output

The document contains programs to implement various graph search algorithms like depth first search, breadth first search, alpha-beta pruning, A* search, and AO* search. It includes the code for each algorithm along with sample outputs and a conclusion stating each program was executed successfully.

Uploaded by

it's technical
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Output

The document contains programs to implement various graph search algorithms like depth first search, breadth first search, alpha-beta pruning, A* search, and AO* search. It includes the code for each algorithm along with sample outputs and a conclusion stating each program was executed successfully.

Uploaded by

it's technical
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Name:Likith Karkera Roll no: 19013

N
Name:Ravend Kumar Ramesh Kumar Upadhyay Roll no-19041

Practical no 1a:
Aim: Write a program to implement depth first search algorithm.
Program:
graph = {

'9' : ['3','6'],

'3' : ['2', '4'],

'6' : ['8'],

'2' : [],

'4' : [],

'8' : []

visited = set()

def dfs(visited, graph, node):

if node not in visited:

print (node)

visited.add(node)

for neighbour in graph[node]:


dfs(visited, graph, neighbour)

print("Following is the Depth-First Search")

dfs(visited, graph, '9')

Output:

Result: The above program to Write a program to implement depth


first search algorithm has been executed successfully.
Practical no:1b
Aim:Write a program to implement breadth first search algorithm.
Program:
graph = {

'9' : ['3','6'],

'3' : ['2', '4'],

'6' : ['8'],

'2' : [],

'4' : [],

'8' : []

visited = []

queue = []

def bfs(visited, graph, node):

visited.append(node)

queue.append(node)

while queue:

m = queue.pop(0)

print (m, end = " ")


for neighbour in graph[m]:

if neighbour not in visited:

visited.append(neighbour)

queue.append(neighbour)

print("Following is the Breadth-First Search")

bfs(visited, graph, '9')

Output:

Result: The above program to Write a program to implement breadth


first search algorithm has been executed successfully.
Practical no:2a
Aim: Write a program to simulate 4-Queen/N-Queen problem.
Program:
class QueenChessBoard:

def __init__(self, size):

self.size = size

self.columns = []

def place_in_next_row(self, column):

self.columns.append(column)

def remove_in_current_row(self):

return self.columns.pop()

def is_this_column_safe_in_next_row(self, column):

row = len(self.columns)

for queen_column in self.columns:

if column == queen_column:

return False

for queen_row, queen_column in enumerate(self.columns):

if queen_column - queen_row == column - row:

return False
for queen_row, queen_column in enumerate(self.columns):

if ((self.size - queen_column) - queen_row

== (self.size - column) - row):

return False

return True

def display(self):

for row in range(self.size):

for column in range(self.size):

if column == self.columns[row]:

print('Q', end=' ')

else:

print('.', end=' ')

print()

def solve_queen(size):

"""Display a chessboard for each possible configuration of placing n


queens

on an n x n chessboard and print the number of such


configurations."""

board = QueenChessBoard(size)

number_of_solutions = 0
row = 0

column = 0

while True:

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

if (column == size or row == size):

if row == size:

board.display()

print()

number_of_solutions += 1

board.remove_in_current_row()

row -= 1

try:

prev_column = board.remove_in_current_row()
except IndexError:

break

row -= 1

column = 1 + prev_column

print('Number of solutions:', number_of_solutions)

n = int(input('Enter n: '))

solve_queen(n)
Output:

Result: The above program to Write a program to simulate 4-


Queen/N-Queen problem has been executed successfully.
Practical no:2b
Aim: Write a program to solve lower of Hanoi problem.
Program:
def moveTower(height,fromPole, toPole, withPole):

if height >= 1:

moveTower(height-1,fromPole,withPole,toPole)

moveDisk(fromPole,toPole)

moveTower(height-1,withPole,toPole,fromPole)

def moveDisk(fp,tp):

print("moving disk from",fp,"to",tp)

moveTower(3,"A","B","C")
Output:

Result: The above program to Write a program to solve lower of Hanoi


problem has been executed successfully.
Practical no:3a
Aim:Write a program to implement alpha beta search.
Program:
tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]

root = 0

pruned = 0

def children(branch, depth, alpha, beta):

global tree

global root

global pruned

i=0

for child in branch:

if type(child) is list:

(nalpha, nbeta) = children(child, depth + 1, alpha, beta)

if depth % 2 == 1:

beta = nalpha if nalpha < beta else beta

else:

alpha = nbeta if nbeta > alpha else alpha

branch[i] = alpha if depth % 2 == 0 else beta


i += 1

else:

if depth % 2 == 0 and alpha < child:

alpha = child

if depth % 2 == 1 and beta > child:

beta = child

if alpha >= beta:

pruned += 1

break

if depth == root:

tree = alpha if root == 0 else beta

return (alpha, beta)

def alphabeta(in_tree=tree, start=root, upper=-15, lower=15):

global tree

global pruned

global root

(alpha, beta) = children(tree, start, upper, lower)

if __name__ == "__main__":

print ("(alpha, beta): ", alpha, beta)

print ("Result: ", tree)


print ("Times pruned: ", pruned)

return (alpha, beta, tree, pruned)

if __name__ == "__main__":

alphabeta(None)

Output:

Result: The above program to Write a program to implement alpha


beta search has been executed successfully.
Practical no:3b
Aim: Write a program for Hill climbing problem.
Program:
import math

increment = 0.1

startingPoint = [1, 1]

point1 = [1,5]

point2 = [6,4]

point3 = [5,2]

point4 = [2,1]

def distance(x1, y1, x2, y2):

dist = math.pow(x2-x1, 2) + math.pow(y2-y1, 2)

return dist

def sumOfDistances(x1, y1, px1, py1, px2, py2, px3, py3, px4, py4):

d1 = distance(x1, y1, px1, py1)

d2 = distance(x1, y1, px2, py2)

d3 = distance(x1, y1, px3, py3)

d4 = distance(x1, y1, px4, py4)

return d1 + d2 + d3 + d4
def newDistance(x1, y1, point1, point2, point3, point4):

d1 = [x1, y1]

d1temp = sumOfDistances(x1, y1, point1[0],point1[1],


point2[0],point2[1], point3[0],point3[1], point4[0],point4[1] )

d1.append(d1temp)

return d1

minDistance = sumOfDistances(startingPoint[0], startingPoint[1],


point1[0],point1[1], point2[0],point2[1], point3[0],point3[1],
point4[0],point4[1] )

flag = True

def newPoints(minimum, d1, d2, d3, d4):

if d1[2] == minimum:

return [d1[0], d1[1]]

elif d2[2] == minimum:

return [d2[0], d2[1]]

elif d3[2] == minimum:

return [d3[0], d3[1]]

elif d4[2] == minimum:

return [d4[0], d4[1]]

i=1

while flag:
d1 = newDistance(startingPoint[0]+increment, startingPoint[1],
point1, point2, point3, point4)

d2 = newDistance(startingPoint[0]-increment, startingPoint[1],
point1, point2, point3, point4)

d3 = newDistance(startingPoint[0], startingPoint[1]+increment,
point1, point2, point3, point4)

d4 = newDistance(startingPoint[0], startingPoint[1]-increment,
point1, point2, point3, point4)

print (i,' ', round(startingPoint[0], 2), round(startingPoint[1], 2))

minimum = min(d1[2], d2[2], d3[2], d4[2])

if minimum < minDistance:

startingPoint = newPoints(minimum, d1, d2, d3, d4)

minDistance = minimum

i+=1

else:

flag = False
Output:

Result: The above program to Write a program for Hill climbing


problem has been executed successfully.
Practical no 4a
Aim: Write a program to implement A* algorithm.
Program:
from simpleai.search import SearchProblem, astar

GOAL = 'HELLO WORLD'

class HelloProblem(SearchProblem):

def actions(self, state):

if len(state) < len(GOAL):

return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ')

else:

return []

def result(self, state, action):

return state + action

def is_goal(self, state):

return state == GOAL

def heuristic(self, state):

wrong = sum([1 if state[i] != GOAL[i] else 0

for i in range(len(state))])

missing = len(GOAL) - len(state)


return wrong + missing

problem = HelloProblem(initial_state='')

result = astar(problem)

print(result.state)

print(result.path())

Output:

Result: The above program to Write a program to implement A*


algorithm has been executed successfully.
Practical no 4b
Aim: Write a program to implement AO* algorithm.
Program:
def AOStar():

list1=['A','B','C','D','E','F','G','H']

list2=[1,2,3,4,5,6,0,1]

lstgraph=['A',['B',['D','E']],['C','F',['G','H']]]

startnode=lstgraph[0]

startindex=list1.index(startnode)

startcost=list2[startindex]

sgn=startcost

print("Start Node :",startnode,"\nInitial Node Cost :",startcost)

listpath=[]

listcost=[]

listtotalcost=[]

iter1=1

while iter1<len(lstgraph):

lsttemp=[]
lsttemp=lstgraph[iter1]

strtemp=str(lsttemp)

sgn=startcost

print("\nNodes to Process : ",lsttemp,len(lsttemp))

listp=[]

listp.append(startnode)

listc=[]

listc.append(startcost)

lenlsttemp=str(lsttemp).count(",")+1

print("Actual Number of Nodes to Process ",strtemp,lenlsttemp)

for var1 in strtemp:

if var1 in list1:

indx=list1.index(var1)

gn=list2[indx]

sgn=sgn+gn

listp.append(var1)

listc.append(gn)

listpath.append(listp)

listcost.append(listc)

listtotalcost.append(sgn)
iter1=iter1+1

print("\nPaths Processed : ",listpath)

print("Processed Cost :",listcost)

print("Total Cost : ",listtotalcost)

opathcost=min(listtotalcost)

opathindex=listtotalcost.index(opathcost)

opath=listpath[opathindex]

print("\nOptimal Path : ",opath)

print("Cost :",opathcost)

AOStar()
Output:

Result: The above program to Write a program to implement AO*


algorithm has been executed successfully.
Practical no:5a
Aim: Write a program to solve water jug problem.
Program:
capacity = (12,8,5)

x = capacity[0]

y = capacity[1]

z = capacity[2]

memory = {}

ans = []

def get_all_states(state):

a = state[0]

b = state[1]

c = state[2]

if(a==6 and b==6):

ans.append(state)

return True

if((a,b,c) in memory):

return False

memory[(a,b,c)] = 1
if(a>0):

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

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

if(b>0):

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

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

if(c>0):

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

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)
Output:

Result: The above program to Write a program to solve water jug


problem has been executed successfully.
Practical no:5b
Aim: Design the simulation of tic – tac – toe game using min-max
algorithm.

Program:
import os

import time

board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']

player = 1

Win = 1

Draw = -1

Running = 0

Stop = 1

Game = Running

Mark = 'X'

def DrawBoard():

print(" %c | %c | %c " % (board[1],board[2],board[3]))

print("___|___|___")

print(" %c | %c | %c " % (board[4],board[5],board[6]))

print("___|___|___")
print(" %c | %c | %c " % (board[7],board[8],board[9]))

print("___|___|___ ")

def CheckPosition(x):

if(board[x] == ' '):

return True

else:

return False

def CheckWin():

global Game

if(board[1] == board[2] and board[2] == board[3] and board[1] != ' '):

Game = Win

elif(board[4] == board[5] and board[5] == board[6] and board[4] != '


'):

Game = Win

elif(board[7] == board[8] and board[8] == board[9] and board[7] != '


'):

Game = Win

elif(board[1] == board[4] and board[4] == board[7] and board[1] != '


'):

Game = Win
elif(board[2] == board[5] and board[5] == board[8] and board[2] != '
'):

Game = Win

elif(board[3] == board[6] and board[6] == board[9] and board[3] != '


'):

Game=Win

elif(board[1] == board[5] and board[5] == board[9] and board[5] != '


'):

Game = Win

elif(board[3] == board[5] and board[5] == board[7] and board[5] != '


'):

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("Player 1 [X] --- Player 2 [O]\n")

print()

print()
print("Please Wait...")

time.sleep(1)

while(Game == Running):

os.system('cls')

DrawBoard()

if(player % 2 != 0):

print("Player 1's chance")

Mark = 'X'

else:

print("Player 2's chance")

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")

Output:
Result: The above program to Design the simulation of tic – tac – toe
game using min-max algorithm has been executed successfully.
Practical no:6a
Aim: Write a program to solve Missionaries and Cannibals problem.

Program:
import math

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 __eq__(self, other):

return self.cannibalLeft == other.cannibalLeft and


self.missionaryLeft == other.missionaryLeft \

and self.boat == other.boat and self.cannibalRight ==


other.cannibalRight \

and self.missionaryRight == other.missionaryRight

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)

if new_state.is_valid():

new_state.parent = cur_state

children.append(new_state)

new_state = State(cur_state.cannibalLeft - 2,
cur_state.missionaryLeft, 'right',

cur_state.cannibalRight + 2, cur_state.missionaryRight)

if new_state.is_valid():

new_state.parent = cur_state

children.append(new_state)

new_state = State(cur_state.cannibalLeft - 1,
cur_state.missionaryLeft - 1, 'right',

cur_state.cannibalRight + 1, cur_state.missionaryRight +
1)

if new_state.is_valid():

new_state.parent = cur_state

children.append(new_state)

new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft


- 1, 'right',
cur_state.cannibalRight, cur_state.missionaryRight + 1)

if new_state.is_valid():

new_state.parent = cur_state

children.append(new_state)

new_state = State(cur_state.cannibalLeft - 1,
cur_state.missionaryLeft, 'right',

cur_state.cannibalRight + 1, cur_state.missionaryRight)

if new_state.is_valid():

new_state.parent = cur_state

children.append(new_state)

else:

new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft


+ 2, 'left',

cur_state.cannibalRight, cur_state.missionaryRight - 2)

if new_state.is_valid():

new_state.parent = cur_state

children.append(new_state)

new_state = State(cur_state.cannibalLeft + 2,
cur_state.missionaryLeft, 'left',

cur_state.cannibalRight - 2, cur_state.missionaryRight)

if new_state.is_valid():
new_state.parent = cur_state

children.append(new_state)

new_state = State(cur_state.cannibalLeft + 1,
cur_state.missionaryLeft + 1, 'left',

cur_state.cannibalRight - 1, cur_state.missionaryRight -
1)

if new_state.is_valid():

new_state.parent = cur_state

children.append(new_state)

new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft


+ 1, 'left',

cur_state.cannibalRight, cur_state.missionaryRight - 1)

if new_state.is_valid():

new_state.parent = cur_state

children.append(new_state)

new_state = State(cur_state.cannibalLeft + 1,
cur_state.missionaryLeft, 'left',

cur_state.cannibalRight - 1, cur_state.missionaryRight)

if new_state.is_valid():

new_state.parent = cur_state

children.append(new_state)
return children

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)

if __name__ == "__main__":

main()
Output:

Result: The above program to Write a program to solve Missionaries


and Cannibals problem has been executed successfully.
Practical no:6b
Aim: Design an application to simulate number puzzle problem .
Program:
from __future__ import print_function

from simpleai.search import astar, SearchProblem

from simpleai.search.viewers import WebViewer

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_):

return '\n'.join(['-'.join(row) for row in list_])

def string_to_list(string_):

return [row.split('-') for row in string_.split('\n')]

def find_location(rows, element_to_find):

for ir, row in enumerate(rows):

for ic, element in enumerate(row):


if element == element_to_find:

return ir, ic

goal_positions = {}

rows_goal = string_to_list(GOAL)

for number in '12345678e':

goal_positions[number] = find_location(rows_goal, number)

class EightPuzzleProblem(SearchProblem):

def actions(self, state):

rows = string_to_list(state)

row_e, col_e = find_location(rows,'e')

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
def result(self, state, action):

rows = string_to_list(state)

row_e, col_e = find_location(rows, 'e')

row_n, col_n = find_location(rows, action)

rows[row_e][col_e], rows[row_n][col_n] = rows[row_n][col_n],


rows[row_e][col_e]

return list_to_string(rows)

def is_goal(self, state):

return state == GOAL

def cost(self, state1, action, state2):

return 1

def heuristics(self, state):

rows = string_to_list(state)

distance = 0

for number in '12345678e':

row_n, col_n = find_location(rows, number)

row_n_goal, col_n_goal = goal_positions[number]

distance += abs(row_n - row_n_goal) + abs(col_n - col_n_goal)

return distance

result = astar(EightPuzzleProblem(INITIAL))
for action, state in result.path():

print("Move number", action)

print(state)
Output:

Result: The above program to Design an application to simulate


number puzzle problem has been executed successfully.
Practical no:7a
Aim: Write a program to shuffle Deck of cards .

Program:
import itertools, random

deck =
list(itertools.product(range(1,52),['Spade','Heart','Diamond','Club']))

random.shuffle(deck)

print("Cards are:")

for i in range(13):

print(deck[i][0], " of ", deck[i][1])


Output:

Result: The above program to Write a program to shuffle Deck of


cards has been executed successfully.
Practical no:7b
Aim: Solve traveling salesman problem using artificial intelligence
technique.

Program:
dictpath={

'A':{'B':3,'C':1,'D':8},

'B':{'D':4},

'C':{'D':5},

'D':{'':0}

print(dictpath)

lstnode=[]

for nodes in dictpath.keys():

lstnode.append(nodes)

print(lstnode)

lstnn=[]

lstcc=[]

lsttc=[]

for node,path in dictpath.items():


for it1 in path:

print("\n",node,"-",it1,":",path[it1])

if node == lstnode[0]:

for node1,path1 in dictpath.items():

lstn1=[]

lstc1=[]

if it1 == node1:

for it2 in path1:

print(node1,"-",it2,":",path1[it2])

lstn1.append(node)

lstn1.append(node1)

lstn1.append(it2)

lstc1.append(path[it1])

lstc1.append(path1[it2])

cost=path[it1]+path1[it2]

print(lstn1)

print(lstc1)

print(cost)

lstnn.append(list(lstn1))
lstcc.append(list(lstc1))

lsttc.append(cost)

print("\nFinal Paths and Cost")

print(lstnn)

print(lstcc)

print(lsttc)

minindx=min(lsttc)

indx=lsttc.index(minindx)

print("\nOptimal Path :",lstnn[indx])

print("Optimal Cost :",minindx)


Output:

Result: The above program to Solve traveling salesman problem using


artificial intelligence technique has been executed successfully
Practical no:8a
Aim: Solve the block of World problem.
Program:
#include <stdio.h>
#include <string.h>
#define MAXN 25
struct TABLE { int LEN; int WHERE; int POS; int LIST[MAXN]; }
BLOCK[MAXN];
void move_block(int B){
int I, A, P, L;
A = BLOCK[B].WHERE;
P = BLOCK[B].POS+1;
L = BLOCK[A].LEN;
for(I = P; I < L; I++){
B = BLOCK[A].LIST[I];
BLOCK[B].WHERE = B;
BLOCK[B].POS = BLOCK[B].LEN;
BLOCK[B].LIST[BLOCK[B].LEN++] = B;
}
BLOCK[A].LEN = P;
}
void move(int B1, int B2){
int I, A, B, P, L, T;
A = BLOCK[B1].WHERE;
B = BLOCK[B2].WHERE;
P = BLOCK[B1].POS;
L = BLOCK[A].LEN;
for(I = P; I < L; I++){
T = BLOCK[A].LIST[I];
BLOCK[T].WHERE = B;
BLOCK[T].POS = BLOCK[B].LEN;
BLOCK[B].LIST[BLOCK[B].LEN++] = T;
}
BLOCK[A].LEN = P;
}
int main(){
int N, I, A, B;
char AC[5], WH[5];
scanf("%d", &N);
for(I = 0; I < N; I++){
BLOCK[I].LEN = 1;
BLOCK[I].WHERE = I;
BLOCK[I].POS = 0;
BLOCK[I].LIST[0] = I;
}
while(scanf("%s", AC)){
if(strcmp(AC, "quit") == 0)
break;
scanf("%d%s%d", &A, WH, &B);
if(A < 0 || A >= N || B < 0 || B >= N)
continue;
if(BLOCK[A].WHERE == BLOCK[B].WHERE)
continue;
if(strcmp(AC, "move") == 0)
move_block(A);
if(strcmp(WH, "onto") == 0)
move_block(B);
move(A, B);
}
for(I = 0; I < N; I++){
printf("%d:", I);
for(A = 0; A < BLOCK[I].LEN; A++)
printf(" %d", BLOCK[I].LIST[A]);
printf("\n");
}
return 0;
}
Output:

Result: The above program to Solve the block of World problem has
been executed successfully.
Practical no:8b
Aim: Solve constraints satisfications problem.
Program:
from __future__ import print_function

from simpleai.search import CspProblem, backtrack, min_conflicts,


MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE,
LEAST_CONSTRAINING_VALUE

variables = ('WA', 'NT', 'SA', 'Q', 'NSW', 'V', 'T')

domains = dict((v, ['red', 'green', 'blue']) for v in variables)

def const_different(variables, values):

return values[0] != values[1]

constraints = [

(('WA', 'NT'), const_different),

(('WA', 'SA'), const_different),

(('SA', 'NT'), const_different),

(('SA', 'Q'), const_different),

(('NT', 'Q'), const_different),

(('SA', 'NSW'), const_different),

(('Q', 'NSW'), const_different),


(('SA', 'V'), const_different),

(('NSW', 'V'), const_different),

my_problem = CspProblem(variables, domains, 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))
Output:

Result: The above program to Solve constraints satisfications problem


has been executed successfully.
Practical no:9a
Aim: Derive the expressions based on Associative law.
Program:
x = input("enter value x:")

y = input("enter value y:")

z = input("enter value z:")

sum1=(int(x) + int(y)) + int(z)

sum2=int(x) + (int(y) + int(z))

print("(x+y)+z= ",sum1)

print("x+(y+z)= ",sum2)

print("(x+y)+z==x+(y+z) is ",sum1 == sum2)


Output:

Result: The above program to Derive the expressions based on


Associative law has been execute successfully.
Practical no:9b
Aim: Derive the expressions based on Distributive law.
Program:
x = input("enter value x:")

y = input("enter value y:")

z = input("enter value z:")

sum1=int(x)*(int(y)+ int(z))

sum2=(int(x)*int(y))+(int(x)* int(z))

print("x(y+z)= ",sum1)

print("xy+xz= ",sum2)

print("x(y+z)==xy+xz is ",sum1 == sum2)


Output:

Result: The above program to Derive the expressions based on


Distributive law has been executed successfully.

You might also like