Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views7 pages

Ai Lab Ex1

The document outlines the implementation of basic search strategies for three problems: the 8-Puzzle Problem, the 8-Queens Problem, and Cryptarithmetic. Each section includes an aim, algorithm, program code, output, and result confirming successful execution. Additionally, it provides viva questions related to the code and its functionality.

Uploaded by

kingspapsfeb2025
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)
13 views7 pages

Ai Lab Ex1

The document outlines the implementation of basic search strategies for three problems: the 8-Puzzle Problem, the 8-Queens Problem, and Cryptarithmetic. Each section includes an aim, algorithm, program code, output, and result confirming successful execution. Additionally, it provides viva questions related to the code and its functionality.

Uploaded by

kingspapsfeb2025
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/ 7

Format QP: 10 24ADPC313- ARTIFICIAL INTELLIGENCE LABORATORY

EX. No. 1a
IMPLEMENT BASIC SEARCH STRATEGIES 8-PUZZLE PROBLEM
DATE:

AIM

To implement the basic search strategies for the 8 Puzzle Problem.

ALGORITHM
Step 1: The code starts by creating a Solution class and then defining the method solve.
Step 2: The function takes in a board as an argument, which is a list of tuples representing the Positions
on the board.
Step 3: It iterates through each position in the list and creates a dictionary with that position's value set
to 0.
Step 4: Then it iterates through all possible moves for that position and returns their number of
occurrences in dict.
Step 5: After this, it loops over all nodes on the board until it finds one where there are no more moves
left to make (i.e., when len(current nodes) == 0).
Step 6: This node will be returned as -1 if found or else its index will be stored into pos_0 so that we can
find out what move was made at that point later on.
Step 7: The next step is finding out what move was made at every node by looping over all possible
moves for each node using self's find next function, which takes in a single node as an argument
and returns any other nodes connected to it via path-finding algorithms like DFS or BFS (see
below).
Step 8: For example, if pos_0 = 1 then self would call: moves = { 0: [1], 1:
Step 9: The code will print the number of paths in a solution.

PROGRAM

class Solution:
def solve(self, board):
state_dict = {} # Renamed `dict` to avoid shadowing the built-in type `dict`
flatten = []
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)
state_dict[flatten] = 0
if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return 0
return self.get_paths(state_dict)
def get_paths(self, state_dict):
cnt = 0
while True:

KINGS COLLEGE OF ENGINEERING 2 KCE/AI & IT /II YR/AI LAB


Format QP: 10 24ADPC313- ARTIFICIAL INTELLIGENCE LABORATORY

current_nodes = [x for x in state_dict if state_dict[x] == cnt]


if len(current_nodes) == 0:
return -1
for node in current_nodes:
next_moves = self.find_next(node)
for move in next_moves:
if move not in state_dict:
state_dict[move] = cnt + 1
if move == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return cnt + 1
cnt += 1
def find_next(self, node):
moves = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
}
results = []
pos_0 = node.index(0)
for move in moves[pos_0]:
new_node = list(node)
new_node[move], new_node[pos_0] = new_node[pos_0], new_node[move]
results.append(tuple(new_node))
return results

# Example usage:
ob = Solution()
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
print ("NO OF MOVES =", ob.solve (matrix))

OUTPUT

NO OF MOVES == 4

RESULT

Thus the program to implement the 8 – puzzles search strategy was successfully implemented
and executed.

KINGS COLLEGE OF ENGINEERING 3 KCE/AI & IT /II YR/AI LAB


Format QP: 10 24ADPC313- ARTIFICIAL INTELLIGENCE LABORATORY

Ex. No: 1b
IMPLEMENT BASIC SEARCH STRATEGIES–8-QUEENS PROBLEM
Date:

AIM

To implement the basic search strategies for the 8-Queens Problem.

ALGORITHM

Step 1: The code starts by asking the user to enter a number.


Step 2: It then creates an NxN matrix with all elements set to 0.
Step 3: The code then defines two functions: attack and N_queens.
Step 4: The function attack checks vertically and horizontally, while the function N_queens checks
diagonally.
Step 5: If either of these functions return true, it means that there is a queen in that position on the
board.
Step 6: The code is a function that will check if there are enough queens on the chessboard.
Step 7: The code starts by defining a function, N_queens (n), which will return true if there are enough
queens and False otherwise.
Step 8: The variable n is used to define how many queens need to be placed on the board for it to be
considered complete.

PROGRAM

def attack(i, j, board):


N = len(board)

# Checking vertically and horizontally


for k in range(N):
if board[i][k] == 1 or board[k][j] == 1:
return True

# Checking diagonally
for k in range(N):
for l in range(N):
if (k + l == i + j) or (k - l == i - j):
if board[k][l] == 1:
return True
return False

def N_queens(n, board):


if n == 0:
return True

for i in range(len(board)):
for j in range(len(board)):

KINGS COLLEGE OF ENGINEERING 4 KCE/AI & IT /II YR/AI LAB


Format QP: 10 24ADPC313- ARTIFICIAL INTELLIGENCE LABORATORY

if not attack(i, j, board) and board[i][j] != 1:


board[i][j] = 1 # Place the queen
if N_queens(n - 1, board):
return True
board[i][j] = 0 # Backtrack
return False

# Main execution
print("Enter the number of queens:")
N = int(input())

# Create an NxN chessboard initialized with 0


board = [[0] * N for _ in range(N)]

if N_queens(N, board):
print(board) # Output the board as a list of lists
else:
print("No solution exists.")

OUTPUT

Enter the number of queens 8


[1, 0, 0,0, 0, 0,0, 0]
[0, 0, 0,0, 1, 0,0, 0]
[0, 0, 0,0, 0, 0,0, 1]
[0, 0, 0,0, 0, 1,0, 0]
[0, 0, 1,0, 0, 0,0, 0]
[0, 0, 0,0, 0, 0,1, 0]
[0, 1, 0,0, 0, 0,0, 0]
[0, 0, 0,1, 0, 0,0, 0]

RESULT

Thus the program to implement the 8 queens search strategy was successfully implemented
and executed.

KINGS COLLEGE OF ENGINEERING 5 KCE/AI & IT /II YR/AI LAB


Format QP: 10 24ADPC313- ARTIFICIAL INTELLIGENCE LABORATORY

Ex.No.1c
IMPLEMENT BASIC SEARCH STRATEGIES - CRYPTARITHMETIC
Date:

AIM
To implement the basic search strategies for the crypt arithmetic.

ALGORITHM
Step 1: The code starts by declaring a variable called num and initializes it to 0.
Step 2: It loops through each letter in the word, assigning a value of 10 to each letter.
Step 3: It checks if any letter is zero or not assigned, returning false if so.
Step 4: The code declares two variables, num for letter frequencies and assigned for letter-to-number
mappings.
Step 5: It iterates through each character in the word to ensure all letters are assigned a value.
Step 6: It increments num by 10 for each valid assignment and updates assigned [char].
Step 7: The solve function is defined with arguments word1, word2, and result to solve the puzzle.
Step 8: It creates a list of possible letter-to-number assignments and iterates over digits 0-9.
Step 9: It checks if a digit is available, assigns it to a letter, and recursively solves the puzzle.
Step 10: The code prints the number of solutions or indicates if no solutions were found.

PROGRAM

def find_value(word,assigned):
num = 0
for charin word:
num= num* 10
num+=assigned[char]
return num
def
is_valid_assignment(word1,word2,result,assi
gned): # First letter of any word cannot be
zero.
If assigned[word1[0]]==0orassigned[word2[0]]==0orassigned[
result[0]] == 0:
returnFals
e return True

def_solve(word1,word2,result,letters,assigned,solutions):
if not letters:
if is_valid_assignment(word1,word2,result,assigned):
num1 = find_value(word1, assigned)
num2 = find_value(word2, assigned)
num_result=find_value(result,assigned
) if num1 + num2 == num_result:

KINGS COLLEGE OF ENGINEERING 6 KCE/AI & IT /II YR/AI LAB


Format QP: 10 24ADPC313- ARTIFICIAL INTELLIGENCE LABORATORY

solutions.append((f'{num1}+{num2}={num_result}',assigned.copy()))
return
for numinrange(10):
if num not in assigned.values():
cur_letter = letters.pop()
assigned[cur_letter]=num
_solve(word1,word2,result,letters,assigned,solutions)
assigned.pop(cur_letter)
letters.append(cur_letter)

def solve(word1,word2,result):
letters=sorted(set(word1)|set(word2)|set(result))
if len(result)>max(len(word1),len(word2))+1orlen(letters)>10:
print('0 Solutions!')
retur
n solutions =
[]
_solve(word1,word2,result,letters,{},solutions)
if solutions:
print('\nSolutions:')
forsolninsolutions:
print(f'{soln[0]}\t{soln[1]}
') if _name_ =='_main_':
print('CRYPTARITHMETICPUZZLESOLVER') print('WORD1
+ WORD2 = RESULT')
word1=input('EnterWORD1:').upper(
)
word2=input('EnterWORD2:').upper(
) result=input('Enter
RESULT:').upper()
ifnot
word1.isalpha()ornotword2.isalpha()ornotresult.isalph
a(): raise TypeError('Inputs should ony consists of
alphabets.')
solve(word1,word2,result)

OUTPUT

CRYPTARITHMETICPUZZLESOLVER
WORD1 + WORD2 = RESULT
Enter WORD1: SEND
Enter WORD2: MORE
Enter RESULT:MONEY
Solutions:
9567+1085=10652{'Y': 2,'S':9,'R':8,'O':0,'N':6,'M':1, 'E':
5,'D':7}
RESULT
Thus the program to implement the crypt arithmetic search strategy was successfully implemented and
executed.

KINGS COLLEGE OF ENGINEERING 7 KCE/AI & IT /II YR/AI LAB


Format QP: 10 24ADPC313- ARTIFICIAL INTELLIGENCE LABORATORY

Viva -Questions

1. What is the Solution class used for in this code?

2. What is the purpose of the attack function in the code?

3. How is the chessboard represented and initialized in the code?

4. What does the N_queens function attempt to achieve?

5. How does the code determine if a solution to the N-Queens problem has been found?

KINGS COLLEGE OF ENGINEERING 8 KCE/AI & IT /II YR/AI LAB

You might also like