AI Record Final
AI Record Final
DATE:
AIM:
The aim of this project is to solve the 8-puzzle problem. The goal is to find the shortest
sequence of moves to arrange the tiles from a given starting position to the target configuration.
ALGORITHM:
1. Start with the puzzle's initial state and the goal state.
2. Create a list to keep track of states to explore.
3. Repeat:
● Pick the state that looks closest to the solution (based on how far the tiles are from
their correct positions).
● If it’s the goal state, stop.
● Otherwise, move the blank tile in all possible directions to create new states.
● Add these new states to the list to explore later.
4. Stop when you find the goal or when there are no more states to explore.
PROGRAM:
import itertools
class PuzzleState:
self.board = board
self.moves = moves
self.prev = prev
self.blank_pos = board.index(0)
goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
def get_neighbors(self):
neighbors = []
moves = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Up, Down, Left, Right
x, y = self.blank_pos % 3, self.blank_pos // 3
new_blank_pos = ny * 3 + nx
new_board = list(self.board)
new_board[self.blank_pos], new_board[new_blank_pos] =
new_board[new_blank_pos], new_board[self.blank_pos]
return neighbors
def a_star(start_board):
start_state = PuzzleState(start_board)
open_list = []
closed_set = set()
heappush(open_list, start_state)
while open_list:
current_state = heappop(open_list)
if current_state.board == goal_state.board:
return current_state
closed_set.add(tuple(current_state.board))
if tuple(neighbor.board) in closed_set:
continue
heappush(open_list, neighbor)
return None
def print_solution(state):
path = []
while state:
path.append(state.board)
state = state.prev
print_board(board)
print()
def print_board(board):
print()
def main():
# Example starting board (you can change this to any solvable configuration)
start_board = [1, 2, 3, 4, 5, 6, 7, 8, 0]
solution = a_star(start_board)
if solution:
print("Solution found!")
print_solution(solution)
else:
if __name__ == "__main__":
main()
OUTPUT:
Solution found!
123
456
78.
RESULT:
Thus the output for implementation of 8 queens problem is executed and verified.
EX.NO:1.b IMPLEMENTATION OF 8-QUEENS PROBLEM
DATE:
AIM:
ALGORITHM:
● Create an N x N board with all cells set to False (no queens placed).
3 Place Queens:
● Check if placing a queen is safe (no other queens in the same row, column, or
diagonals).
● If safe, place the queen and move to the next column (call the function
recursively).
5 Repeat:
6 Output:
● If a solution is found, display the board; if not, indicate that no solution exists.
PROGRAM:
def print_board(board):
print()
for i in range(col):
if board[row][i]:
return False
if board[i][j]:
return False
if board[i][j]:
return False
return True
return True
for i in range(len(board)):
if is_safe(board, i, col):
board[i][col] = True
return True
board[i][col] = False
return False
def main():
N=8
if solve_queens(board, 0):
print_board(board)
else:
if __name__ == "__main__":
main()
OUTPUT:
Q.......
......Q.
....Q...
.......Q
.Q......
...Q....
.....Q..
..Q.....
RESULT:
Thus the output for implementation of 8 queens problem is executed and verified.
EX.NO:1.c IMPLEMENTATION OF CRYPTARITHMETIC PROBLEM
DATE:
AIM:
The aim of this program is to solve cryptarithmetic puzzles by substituting letters with
digits to form valid equations. It uses permutations to explore all possible digit assignments
and checks for valid solutions. The program outputs the mapping of letters to digits if a solution
is found.
ALGORITHM:
1. Parse the puzzle to get the LHS and RHS of the equation.
2. Collect unique letters from both sides and ensure there are 10 or fewer.
3. Generate digit combinations for the letters using permutations.
4. Replace letters with digits and check if the equation holds true.
5. Return the solution if found, or indicate no solution exists.
PROGRAM:
def solve_cryptarithmetic(puzzle):
parts = puzzle.split('=')
if len(parts) != 2:
lhs = parts[0].split('+')
rhs = parts[1]
try:
return letter_to_digit
except ValueError:
return None
solution = solve_cryptarithmetic(puzzle)
if solution:
print("Solution found:")
print(f"{letter} = {digit}")
else:
Solution found:
O=0
R=8
N=6
E=5
M=1
D=7
Y=2
S=9
RESULT:
Thus the output for implementation of cryptarithmetic problem is executed and verified.
EX.NO:2 IMPLEMENTATION OF A* AND MEMORY BOUND A*
DATE:
AIM:
The A* and memory-bounded A* algorithms aim to find the shortest path in a graph
from a starting point to a goal. They use a priority queue to explore paths while balancing cost
and estimated distance to the goal. The memory-bounded version limits memory usage during
the search.
ALGORITHM:
A* Search Algorithm
1. Initialize: Create the graph and add the starting vertex to a priority queue.
2. Search:
o While the queue is not empty:
▪ Dequeue the lowest-cost vertex.
▪ If it’s the goal, reconstruct and return the path.
▪ For each neighbor, calculate the cost and update if it's lower.
3. Return Path: If the goal is reached, trace back the path.
1. Initialize: Create the graph and add the starting vertex to a priority queue.
2. Search:
o While the queue is not empty:
▪ Dequeue the lowest-cost vertex.
▪ If it’s the goal, reconstruct and return the path.
▪ For each neighbor, calculate the cost and update if it's lower.
▪ If the memory limit is exceeded, return "Memory limit exceeded."
3. Return Path: If the goal is reached, trace back the path.
PROGRAM:
import heapq
class Graph:
def __init__(self):
self.vertices = {}
self.vertices[id] = Vertex(id)
self.vertices[from_id].add_neighbor(to_id, cost)
class Vertex:
self.id = id
self.neighbors = {}
self.neighbors[neighbor_id] = cost
cost_so_far = {start_id: 0}
while frontier:
if current_id == goal_id:
break
cost_so_far[neighbor_id] = new_cost
came_from[neighbor_id] = current_id
path.append(current_id)
current_id = came_from[current_id]
path.append(start_id)
cost_so_far = {start_id: 0}
while frontier:
if current_id == goal_id:
break
came_from[neighbor_id] = current_id
# Example usage
graph = Graph()
graph.add_vertex(vertex_id)
edges = [("A", "B", 5), ("A", "C", 3), ("B", "D", 4), ("C", "D", 2),
("C", "E", 6), ("D", "F", 7), ("E", "F", 4), ("E", "G", 5),
graph.add_edge(*edge)
# Run A* search
start_id = "A"
goal_id = "G"
memory_limit = 1000
RESULT:
Thus the output for implementation of A* and memory bound A* executed and
verified.
EX.NO:3 IMPLEMENTATION OF MIN-MAX ALGORITHM
DATE:
AIM:
The aim of this program is to create a simple Rock-Paper-Scissors game where a player
can compete against a randomly choosing AI opponent. The program allows for repeated
rounds of play until the player decides to exit. It determines and announces the winner based
on the standard rules of the game.
ALGORITHM:
1. Start Game:
2. Print a welcome message.
3. Define Moves:
4. List possible moves: ['rock', 'paper', 'scissors'].
5. Game Loop:
6. While true:
a. Prompt player for their move or "quit" to exit.
b. If "quit", exit the loop.
c. If input is invalid, print an error and repeat.
7. AI Move:
8. Randomly select an AI move from the list.
9. Determine Winner:
10. Compare player and AI moves:
a. If same, declare a draw.
b. If player wins, print "You win!".
c. If AI wins, print "AI wins!".
11. Repeat:
12. Go back to step 3 for the next round.
PROGRAM:
import random
if player_move == ai_move:
else:
def play_game():
print("Welcome to Rock-Paper-Scissors!")
while True:
if player_move == 'quit':
break
continue
ai_move = random.choice(moves)
print(result)
play_game()
OUTPUT:
Welcome to Rock-Paper-Scissors!
Enter rock, paper, or scissors (or 'quit' to exit): rock
AI chose: paper
AI wins!
Enter rock, paper, or scissors (or 'quit' to exit): paper
AI chose: paper
It's a draw!
Enter rock, paper, or scissors (or 'quit' to exit): scissor
Invalid input! Please try again.
Enter rock, paper, or scissors (or 'quit' to exit): scissors
AI chose: paper
You win!
RESULT:
Thus the output for implementattion of min-max algorithm for game theory is
executed and verified
EX.NO:4 IMPLEMENTATION OF CONSTRAINT SATISFACTION
PROBLEMS
DATE:
AIM:
The aim of this program is to solve the map coloring problem by ensuring that no
adjacent regions have the same color. It uses a backtracking algorithm to explore different color
assignments. The program outputs a valid coloring solution or states if none exists.
ALGORITHM:
1. Initialize Variables:
● Check if assigning color to region is safe by verifying that no adjacent regions have
the same color.
4. Call map_coloring(0):
""" Check if it's safe to assign the color to the region. """
if colors[neighbor] == color:
return False
return True
""" Utility function to solve the map coloring problem using backtracking. """
if index == len(regions):
region = regions[index]
return True
colors[region] = -1 # Backtrack
colors = {region: -1 for region in regions} # Initialize all regions with no color
if map_coloring_util(regions, colors, adjacency, 0, num_colors):
return colors
else:
return None
adjacency = {
# Number of colors
num_colors = 3
if solution:
print('Solution:', colored_solution)
else:
print('No solution found.')
OUTPUT:
RESULT:
Thus the output for implementation of Constraint Satisfication problem is executed and
verified.
EX.NO:5 IMPLEMENTATION OF PROPOSITIONAL MODEL
CHECKING ALGORITHMS
DATE:
AIM:
ALGORITHM:
1.Initialize:
3.Backtrack:
● Remove the current state from visited before returning False (to allow for other
paths).
4.Return Result:
PROGRAM:
class State:
self.name = name
self.transitions = {}
def add_transition(self, action, next_state):
self.transitions[action] = next_state
class ModelChecker:
self.initial_state = initial_state
visited = set()
if state in visited:
return False
visited.add(state)
if property_func(state):
return True
return True
visited.remove(state)
return False
# Define states
s0 = State("s0")
s1 = State("s1")
s2 = State("s2")
# Define transitions
s0.add_transition("a", s1)
s1.add_transition("b", s2)
s2.add_transition("c", s0)
initial_state = s0
checker = ModelChecker(initial_state)
def property_function(state):
result = checker.check_property(property_function)
RESULT:
AIM:
The aim of the program is to implement three logic-based reasoning strategies: forward
chaining, backward chaining, and resolution. It allows users to infer conclusions from given
rules and facts, demonstrating how each method derives knowledge.
ALGORITHM:
3. Resolution Algorithm
PROGRAM:
class ForwardChaining:
def __init__(self, rules, facts):
self.rules = rules
self.facts = set(facts)
def infer(self):
new_facts = True
while new_facts:
new_facts = False
self.facts.add(rule['conclusion'])
new_facts = True
return self.facts
class BackwardChaining:
self.rules = rules
self.facts = set(facts)
if goal in self.facts:
return True
return True
return False
class Resolution:
self.clauses = clauses
resolvents = []
if -literal in clause2:
resolvents.append(new_clause)
return resolvents
negated_goal = {-goal}
new_resolvents = clauses[:]
while True:
if frozenset() in new_clauses:
return True
if new_clauses.issubset(set(new_resolvents)):
return False
new_resolvents.extend(new_clauses)
# Forward Chaining
rules = [
facts = ['A']
fc = ForwardChaining(rules, facts)
fc.infer()
# Backward Chaining
rules_bc = [
facts_bc = ['A']
bc = BackwardChaining(rules_bc, facts_bc)
goal = 'C'
# Resolution
clauses = [
frozenset({1, 2}), # P or Q
resolution = Resolution(clauses)
goal_res = 3 # R
if __name__ == "__main__":
main()
OUTPUT:
RESULT:
Thus the output for implementation of forward chaining, backward chaining and
resolution strategies is executed and verified.
EX.NO:7 IMPLEMENTATION OF NAÏVE BAYES MODELS
DATE:
AIM:
The aim of the Naïve Bayes classifier implementation is to demonstrate a simple and
effective probabilistic classification method based on Bayes' theorem.
ALGORITHM:
2. Preprocess:
3.Calculate Probabilities:
4.Predict:
● For each test instance, compute the class with the highest probability using:
P(Class∣Features)∝P(Class)×P(Features∣Class)P(Class | Features) \propto P(Class)
\times P(Features | Class)P(Class∣Features)∝P(Class)×P(Features∣Class)
PROGRAM:
import pandas as pd
# Sample Data
data = {
'Feature1': [1, 2, 1, 2, 1, 2, 1, 2],
# Create DataFrame
df = pd.DataFrame(data)
X = df[['Feature1', 'Feature2']]
y = df['Label']
y_pred = model.predict(X_test)
# Output results
Accuracy: 0.50
Classification Report:
precision recall f1-score support
accuracy 0.50 2
macro avg 0.25 0.50 0.33 2
weighted avg 0.25 0.50 0.33 2
RESULT :
Thus the output for implementation of naïve’s bayes model is executed and verified.
EX.NO:8 IMPLEMENTATION OF BAYESIAN NETWORKS AND PERFORM
INFERENCES
DATE:
AIM:
The aim of the Bayesian network program is to model the probabilistic relationships
between variables using a structured graphical representation. It allows for efficient inference,
enabling users to compute the likelihood of certain outcomes given specific evidence.
ALGORITHM:
1.Define Structure:
2.Define Probabilities:
● For each node, create Conditional Probability Tables (CPTs) that represent the
probabilities of the node given its parents.
4.Verify Model:
5.Perform Inference:
● Use inference algorithms (e.g., Variable Elimination) to query the model for
probabilities given specific evidence.
6.Output Results:
PROGRAM:
evidence=['Rain', 'Accident'],
evidence_card=[2, 2])
[0.1, 0.3]],
evidence=['Traffic'],
evidence_card=[2])
assert model.check_model()
# Perform inference
infer = VariableElimination(model)
# Example queries
# Output results
print(result_arrival)
print("\nP(Traffic | Arrival=True):")
print(result_traffic)
OUTPUT:
P(Traffic | Arrival=True):
+------------+----------------+
| Traffic | phi(Traffic) |
+============+================+
| Traffic(0) | 0.3278 |
+------------+----------------+
| Traffic(1) | 0.6722 |
+------------+----------------+
RESULT:
Thus the output is verified for implementation of bayesian networks and perform
inference is executed and verified.