0% found this document useful (0 votes)
7 views23 pages

Ai Programs

The document contains multiple algorithms and implementations for solving various computational problems, including the 8-puzzle, N-Queens, cryptarithms, A* search, SMA* search, Minimax, and Constraint Satisfaction Problems (CSP). Each section provides code snippets in Python that demonstrate how to implement these algorithms effectively. The document serves as a comprehensive reference for algorithmic problem-solving techniques in programming.

Uploaded by

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

Ai Programs

The document contains multiple algorithms and implementations for solving various computational problems, including the 8-puzzle, N-Queens, cryptarithms, A* search, SMA* search, Minimax, and Constraint Satisfaction Problems (CSP). Each section provides code snippets in Python that demonstrate how to implement these algorithms effectively. The document serves as a comprehensive reference for algorithmic problem-solving techniques in programming.

Uploaded by

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

8 puzzle

class Solution:

def solve(self, board):

dict = {}

flatten = []

for i in range(len(board)):

flatten += board[i]

flatten = tuple(flatten)

dict[flatten] = 0

if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):

return 0

return self.get_paths(dict)

def get_paths(self, dict):

cnt = 0

while True:

current_nodes = [x for x in dict if 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 dict:

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

ob = Solution()

matrix = [

[3, 1, 2],

[4, 7, 5],

[6, 8, 0]

print(ob.solve(matrix))
8queen

print ("Enter the number of queens")

N = int(input())

# here we create a chessboard

# NxN matrix with all elements set to 0

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

def attack(i, j):

#checking vertically and horizontally

for k in range(0,N):

if board[i][k]==1 or board[k][j]==1:

return True

#checking diagonally

for k in range(0,N):

for l in range(0,N):

if (k+l==i+j) or (k-l==i-j):

if board[k][l]==1:

return True

return False

def N_queens(n):

if n==0:

return True

for i in range(0,N):

for j in range(0,N):

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


board[i][j] = 1

if N_queens(n-1)==True:

return True

board[i][j] = 0

return False

N_queens(N)

for i in board:

print (i)
Crypt 1

import itertools

def get_value(word, substitution):

s=0

factor = 1

for letter in reversed(word):

s += factor * substitution[letter]

factor *= 10

return s

def solve2(equation):

# split equation in left and right

left, right = equation.lower().replace(' ', '').split('=')

# split words in left part

left = left.split('+')

# create list of used letters

letters = set(right)

for word in left:

for letter in word:

letters.add(letter)

letters = list(letters)
digits = range(1 0)

for perm in itertools.permutations(digits, len(letters)):

sol = dict(zip(letters, perm))

if sum(get_value(word, sol) for word in left) == get_value(right, sol):

print(' + '.join(str(get_value(word, sol)) for word in left) + " = {} (mapping:


{})".format(get_value(right, sol), sol))

if __name__ == '__main__':

solve2('SEND + MORE = MONEY')


ASTAR 1

def aStarAlgo(start_node, stop_node):

open_set = set(start_node)

closed_set = set()

g = {} #store distance from starting node

parents = {}# parents contains an adjacency map of all nodes

#ditance of starting node from itself is zero

g[start_node] = 0

#start_node is root node i.e it has no parent nodes

#so start_node is set to its own parent node

parents[start_node] = start_node

while len(open_set) > 0:

n = None

#node with lowest f() is found

for v in open_set:

if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):

n=v
if n == stop_node or Graph_nodes[n] == None:

pass

else:

for (m, weight) in get_neighbors(n):

#nodes 'm' not in first and last set are added to first

#n is set its parent

if m not in open_set and m not in closed_set:

open_set.add(m)

parents[m] = n

g[m] = g[n] + weight

#for each node m,compare its distance from start i.e g(m) to the

#from start through n node

else:

if g[m] > g[n] + weight:

#update g(m)

g[m] = g[n] + weight

#change parent of m to n

parents[m] = n

#if m in closed set,remove and add to open

if m in closed_set:

closed_set.remove(m)

open_set.add(m)
if n == None:

print('Path does not exist!')

return None

# if the current node is the stop_node

# then we begin reconstructin the path from it to the start_node

if n == stop_node:

path = []

while parents[n] != n:

path.append(n)

n = parents[n]

path.append(start_node)

path.reverse()

print('Path found: {}'.format(path))

return path

# remove n from the open_list, and add it to closed_list

# because all of his neighbors were inspected

open_set.remove(n)
closed_set.add(n)

print('Path does not exist!')

return None

#define fuction to return neighbor and its distance

#from the passed node

def get_neighbors(v):

if v in Graph_nodes:

return Graph_nodes[v]

else:

return None

#for simplicity we ll consider heuristic distances given

#and this function returns heuristic distance for all nodes

def heuristic(n):

H_dist = {

'A': 11,

'B': 6,

'C': 99,

'D': 1,

'E': 7,

'G': 0,

}
return H_dist[n]

#Describe your graph here

Graph_nodes = {

'A': [('B', 2), ('E', 3)],

'B': [('C', 1),('G', 9)],

'C': None,

'E': [('D', 6)],

'D': [('G', 1)],

aStarAlgo('A', 'G')
SMASTAR

class Node:

def __init__(self, state, parent=None, action=None):

self.state = state

self.parent = parent

self.action = action

# Define the heuristic function (Manhattan distance)

def heuristic(state):

distance = 0

for i in range(9):

if state[i] != 0:

distance += abs(i // 3 - (state[i] - 1) // 3) + abs(i % 3 - (state[i] - 1) % 3)

return distance

# Define the memory usage function

def memory_usage(open_list, closed_list):

return len(open_list) + len(closed_list)

# Define the function to prune memory

def prune_memory(open_list, closed_list):

# Prune the least promising nodes from the open list

open_list.sort(key=lambda x: heuristic(x.state), reverse=True)

open_list[:] = open_list[:len(open_list) // 2] # Keep only the top half of the open list
# Define the function to select the best node

def select_best_node(open_list):

return min(open_list, key=lambda x: heuristic(x.state))

# Define the function to check if a node is the goal state

def is_goal(node):

return node.state == goal_state

# Define the function to generate successors

def generate_successors(node):

successors = []

zero_index = node.state.index(0)

for move in moves[zero_index]:

new_state = list(node.state)

new_state[zero_index], new_state[move] = new_state[move], new_state[zero_index]

successors.append(Node(tuple(new_state), parent=node, action=move))

return successors

# Define the function to check if a successor is redundant

def redundant(successor, open_list, closed_list):

for node in open_list + closed_list:

if node.state == successor.state:

return True

return False
# Define the memory-bounded search function

def MemoryBoundedSearch(initial_state, memory_limit):

node = Node(initial_state)

open_list = [node]

closed_list = []

while open_list:

if memory_usage(open_list, closed_list) > memory_limit:

prune_memory(open_list, closed_list)

# No solution found within memory limit

if not open_list:

return None

current_node = select_best_node(open_list)

# Return the goal node

if is_goal(current_node):

return current_node

open_list.remove(current_node)

closed_list.append(current_node)

for successor in generate_successors(current_node):


if not redundant(successor, open_list, closed_list):

open_list.append(successor)

# No solution found within memory limit

return None

# Define the goal state

goal_state = (1, 2, 3, 4, 5, 6, 7, 8, 0)

# Define the possible moves

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]

# Example usage

initial_state = (1, 2, 3, 4, 5, 6, 0, 7, 8) # Initial state of the puzzle


print("Case 1 with Memory Limit 1")

memory_limit = 1 # Set memory limit

goal_node = MemoryBoundedSearch(initial_state, memory_limit)

if goal_node:

print("Solution found!")

# Print the solution path if needed

while goal_node.parent:

print("Action:", goal_node.action)

print("State:")

print(goal_node.state[:3])

print(goal_node.state[3:6])

print(goal_node.state[6:])

print()

goal_node = goal_node.parent

else:

print("Memory limit exceeded. No solution found within the given memory limit.")

print("\nCase 1 with Memory Limit 10")

memory_limit = 10 # Set memory limit

goal_node = MemoryBoundedSearch(initial_state, memory_limit)

if goal_node:

print("Solution found!")

# Print the solution path if needed


while goal_node.parent:

print("Action:", goal_node.action)

print("State:")

print(goal_node.state[:3])

print(goal_node.state[3:6])

print(goal_node.state[6:])

print()

goal_node = goal_node.parent

else:

print("Memory limit exceeded. No solution found within the given memory limit.")
MINMAX

MAX, MIN = 1000, -1000

def minimax(depth, nodeIndex, maximizingPlayer,values, alpha, beta):

if depth == 3:

return values[nodeIndex]

if maximizingPlayer:

best = MIN

for i in range(0, 2):

val = minimax(depth + 1, nodeIndex * 2 + i,False, values, alpha, beta)

best = max(best, val)

alpha = max(alpha, best)

if beta <= alpha:

break

return best

else:

best = MAX

for i in range(0, 2):

val = minimax(depth + 1, nodeIndex * 2 + i,True, values, alpha, beta)

best = min(best, val)

beta = min(beta, best)

if beta <= alpha:

break

return best
if __name__ == "__main__":

values = [3, 5, 6, 9, 1, 2, 0, -1]

print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX))


CSP

VARIABLES = ["csc", "maths", "phy", "che", "tam", "eng", "bio"]

DOMAIN = ["Monday", "Tuesday", "Wednesday"]

CONSTRAINTS = [

("csc", "maths"),

("csc", "phy"),

("mat", "phy"),

("mat", "che"),

("mat", "tam"),

("phy", "tam"),

("phy", "eng"),

("che", "eng"),

("tam", "eng"),

("tam", "bio"),

("eng", "bio")

def backtrack(assignment):

if len(assignment) == len(VARIABLES):

return assignment

var = select_unassigned_variable(assignment)

for value in DOMAIN:

if consistent(var, value, assignment):

assignment[var] = value
result = backtrack(assignment)

if result is not None:

return result

return None

def select_unassigned_variable(assignment):

for var in VARIABLES:

if var not in assignment.keys():

return var

def consistent(var, value, assignment):

for var1, var2 in CONSTRAINTS:

if var1 == var or var2 == var:

for var3, day in assignment.items():

if (var3 == var2 or var3 == var1) and day == value:

return False

return True

solution = backtrack(dict())

print(solution)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy