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

3 8 (Amar)

The document describes implementing the 8 puzzle problem using an A* search algorithm. It defines the 8 puzzle problem, outlines the rules, and describes representing the puzzle state and defining a heuristic function. It then outlines the steps of the A* search algorithm: initializing the start state, creating open and closed lists, exploring states, and repeating until the goal is reached or no moves remain. It also describes backtracking to find the sequence of moves. Finally, it compares brute force depth-first search, breadth-first search, and branch and bound algorithms for solving the 8 puzzle problem.

Uploaded by

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

3 8 (Amar)

The document describes implementing the 8 puzzle problem using an A* search algorithm. It defines the 8 puzzle problem, outlines the rules, and describes representing the puzzle state and defining a heuristic function. It then outlines the steps of the A* search algorithm: initializing the start state, creating open and closed lists, exploring states, and repeating until the goal is reached or no moves remain. It also describes backtracking to find the sequence of moves. Finally, it compares brute force depth-first search, breadth-first search, and branch and bound algorithms for solving the 8 puzzle problem.

Uploaded by

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

Experiment- 03

Aim: To implement Monkey Banana Problem


Algorithm:
1. Define a State class to represent the state of the monkey, box, and bananas. The class should include:
- monkey_x, monkey_y: The x and y coordinates of the monkey.
- box_x, box_y: The x and y coordinates of the box.
- actions: A list to store the sequence of actions taken to reach this state.
2. Create an empty set visited to keep track of visited states.
3. Create an empty queue queue and enqueue the initial_state.
4. While the queue is not empty:
a. Dequeue the current_state from the front of the queue.
b. Add the (current_state.monkey_x, current_state.monkey_y, current_state.box_x,
current_state.box_y) tuple to the visited set.
c. Check if the current_state is the goal state (i.e., monkey is at target_x, target_y):
- If it is the goal state, return current_state.actions as the solution.
d. Generate possible actions and their resulting states:
- Possible actions include:
- MoveMonkeyLeft
- MoveMonkeyRight
- MoveBoxLeft
- MoveBoxRight
- ClimbOnBox
- ClimbOffBox
- Calculate the new coordinates for the monkey and the box based on each action.
e. For each possible action:
- Create a new new_state object with the updated coordinates.
- Set new_state.actions to be a copy of current_state.actions with the current action appended.
f. Check if the new state is valid:
- Ensure that the monkey, box, and bananas are within the room boundaries (0-4 in both x and y
coordinates).

Shubham A20405220146
Shubham A20405220146
- Check if (new_monkey_x, new_monkey_y, new_box_x, new_box_y) is not in the visited set.
g. If the new state is valid, enqueue new_state into the queue.
5. If the loop exits without finding a solution, return None to indicate that no solution exists.

Code:

Shubham A20405220146
Output:

Subham A20405220146
Experiment- 04
Aim: To implement Tic Tac Toe Problem
Algorithm:

1. Initialize the player (X) and opponent (O) symbols.


2. Create a 3x3 game board filled with empty spaces (' ').
3. Define a function to print the current game board.
4. Define a function to check if a player has won the game by checking rows, columns,
and diagonals.
5. Define a function to check if the game board is full (a draw).
6. Define a function to get the player's move by accepting the row and column input.
7. Implement the Minimax algorithm:
 Define an evaluation function to evaluate the board state.
 Define the Minimax function, which recursively explores all possible moves
and returns the best score.
 The Maximizer tries to maximize the score, and the Minimizer tries to minimize
it.
 The Minimax function keeps track of the best move and its associated score.
8. Define a function to find the best move for the computer using the Minimax
algorithm. Iterate through all possible moves and choose the one with the highest
score.
9. Implement the main game loop:
 Display a welcome message.
 Print the initial game board.
 Start a loop to alternate between player and computer turns until the game ends.
 For the player's turn:
 Get the player's move (row and column) using user input.
 Update the game board with the player's move.
 Check if the player has won. If yes, print a victory message and end
the game.
 Check if the game board is full (a draw). If yes, print a draw message
and end the game.
 For the computer's turn:
 Use the Minimax algorithm to find the best move for the computer.
 Update the game board with the computer's move.
 Check if the computer has won. If yes, print a victory message and end
the game.
 Check if the game board is full (a draw). If yes, print a draw message
and end the game.
10. End the game.

Shubham A20405220146
Fig 4.1: Tic Tac Toe

Shubham A20405220146
Shubham A20405220146
Shubham A20405220146
Shubham A20405220146
Experiment- 05
Aim: Implement 8 Puzzle Problem
8 Puzzle Problem
A 3 by 3 board with 8 tiles (each tile has a number from 1 to 8) and a single empty space is
provided. The goal is to use the vacant space to arrange the numbers on the tiles such that they
match the final arrangement. Four neighbouring (left, right, above, and below) tiles can be
moved into the available area.

Fig 5.1: 8 Puzzle Problem

Rules of the 8-puzzle problem:


1. You can only move a tile into the empty space.
2. Tiles can be moved either horizontally or vertically, but only one position at a time.
3. The objective is to reach the goal state from an initial state using the fewest possible moves.
Solving the 8-puzzle problem is often done using search algorithms like A* search or breadth-
first search. Here's a simplified outline of how you can approach solving it using A* search:
1. State
Representation: Represent the puzzle's state as a data structure. Typically, this involves a
2D array to represent the tile positions.
2. Define the Heuristic: Choose a heuristic function to estimate how close a state is to the goal
state. Common heuristics include the Manhattan distance (sum of distances each tile is away
from its goal position) and the misplaced tiles count (number of tiles not in their goal positions).
3. Initial State: Start with the initial state of the puzzle.

Shubham A20405220146
4. Open and Closed Lists: Create two lists, the "open" list (to store states to be explored) and the
"closed" list (to store states already explored).
5.A Search: Use the A search algorithm to explore states. At each step, consider all possible
moves from the current state, evaluate their cost based on the heuristic function, and select the
one with the lowest cost.
6. RepeatUntil Goal: Continue exploring states and selecting moves until the goal state is
reached or no more moves are possible.
7. Backtracking:Once the goal state is reached, backtrack from the goal state to the initial state to
find the sequence of moves that solved the puzzle.

Figure 1.2: 8 Puzzle Problem Tree

1. DFS (Brute - Force) :


On the state-space tree (Set of all configurations of a particular issue, i.e., all states that may be
reached from the beginning state), we can do a depth-first search.
In this solution, further movements might not always send us closer to the objective, but rather
further away. Regardless of the initial state, the state-space tree searches down the leftmost route
from the root. With this method, an answer node might never be discovered.
2. BFS (Brute - Force) :
We can search the state space tree using a breadth-first approach. It always locates the goal state
that is closest to the root. However, the algorithm tries the same series of movements as DFS
regardless of the initial state.
3. Branch and Bound :

Shubham A20405220146
By avoiding searching in sub-trees which do not include an answer node, an "intelligent" ranking
function, also known as an approximatsion costs function, may frequently speed up the search
for an answer node. However, instead of using the backtracking method, it does a BFS-style
search.
Basically, Branch and Bound involves three different kinds of nodes.
1.A live node is a created node whose children have not yet been formed. 2.The offspring of the
E-node which is a live node, are now being investigated. Or to put it another way, an E-node is a
node that is currently expanding. 3.A created node which is not to be developed or examined
further is referred to as a dead node. A dead node has already extended all of its offspring.
Costs function:
In the search tree, each node Y has a corresponding costs. The next E-node may be found using
the costs function. The E-node with the lowest costs is the next one. The function can be defined
as :
1.C(Y) = g(Y) + h(Y)
2.where
3.g(Y) = the costs of reaching to the current node
4.from the root.
5.h(Y) = the costs of reaching to an answer node from the Y.
The optimum costs function for an algorithm for 8 puzzles is : We suppose that it will costs one
unit to move a tile in any direction. In light of this, we create the following costs function for the
8-puzzle algorithm :
1.c(y) = f(y) + h(y)
2.where
3.f(y) = the path's total length from the root y.
4.and
5.h(y) = the amount of the non-blank tiles which are not in
6.their final goal position (misplaced tiles).
7.To change state y into a desired state, there are at least h(y) movements required.
Final algorithm :
1. In
order to maintain the list of live nodes, algorithm LCSearch employs the functions Least()
and Add().
2. Least() identifies a live node with the least c(y), removes it from the list, and returns it.

Shubham A20405220146
3. Add(y) adds y to the list of live nodes.
4. Add(y) implements the list of live nodes as a min-heap.
The route taken by the aforementioned algorithm to arrive at the final configuration of the 8-
Puzzle from the starting configuration supplied is shown in the diagram below. Keep in mind
that only nodes with the lowest costs function value are extended.

Figure 5.3: 8 Puzzle Tree

Shubham A20405220146
Shubham A20405220146
Shubham A20405220146
Shubham A20405220146
Experiment- 06
Aim: Implement Tower of Hanoi Problem
The Rule For disk movement in TOH:
The rules according to which the disks have to be moved in Tower of Hanoi are the following:
1. Initially, the disks are placed in Increasing Order in size on Tower 1 from top to bottom.
2. the objective is to move them to tower 2, making also use of an auxiliary tower 3.
3. the conditions for moving the disks are:
4. all disks (except the one to be moved) have to be on one of the three towers.
5. Only one disk is possible to move at a time.
6. The only top disk can be moved i.e. taking from the top of one tower and placing on the
top of another tower.
7. A larger disk can never be placed on a smaller disk.
if we will have n number of disk then our aim is to move bottom which is disk n from source to
destination. And then put all other (n-1) disks onto it.

Steps we will follow are:

Step 1 − Move n-1 disks from source to aux

Step 2 − Move nth disk from source to dest

Step 3 − Move n-1 disks from aux to dest

Fig 6.1: Tower of Hanoi

Algorithm TowerOfHanoi(n, source, auxiliary, destination):

if n == 1:

Move disk from source to destination

Shubham A20405220146
return

TowerOfHanoi(n-1, source, destination, auxiliary) // Move n-1 disks from source to auxiliary

Move disk from source to destination // Move the largest disk from source to destination

TowerOfHanoi(n-1, auxiliary, source, destination) // Move n-1 disks from auxiliary to destination

Shubham A20405220146
Experiment- 07
Aim: Implement Water Jug Problem
Algorithm:
1. Import the deque class from the collections module.
2. Define the BFS function with parameters a (capacity of Jug1), b (capacity of Jug2), and target
(the target amount to measure).
3. Initialize a dictionary m to keep track of visited states, a boolean variable isSolvable to check
if a solution exists, and an empty list path to store the path from the initial state to the solution
state.
4. Create a deque q and enqueue the initial state (0, 0) as a tuple (Jug1's current amount, Jug2's
current amount).
5. Perform a BFS traversal while the queue q is not empty:
a. Dequeue the front element u.
b. Check if the state (u[0], u[1]) has already been visited. If so, continue to the next iteration.
c. Check if the current state is valid (within the jug capacities and non-negative).
d. Add the current state to the path list.
e. Mark the current state as visited in the m dictionary.
f. Check if the target amount is reached in either Jug1 or Jug2. If so, set isSolvable to True and
break from the loop.
g. Enqueue the following states:
- Filling Jug2 to its maximum capacity.
- Filling Jug1 to its maximum capacity.
- Pouring water from Jug2 to Jug1 and vice versa, while maintaining valid states.
- Emptying Jug2 and Jug1 separately.
6. If a solution is found (isSolvable is True), print the path from the initial state to the solution
state.
7. If no solution is found (isSolvable is still False), print "No solution."
Code:

Shubham A20405220146
Shubham A20405220146
Output:

Shubham A20405220146
Experiment- 08
Aim: Implement Travelling Salesman Problem

The traveling salesman problems abide by a salesman and a set of cities. The salesman has to
visit every one of the cities starting from a certain one (e.g., the hometown) and to return to the
same city. The challenge of the problem is that the traveling salesman needs to minimize the
total length of the trip. Suppose the cities are x 1 x2..... xn where cost cij denotes the cost of
travelling from city xi to xj. The travelling salesperson problem is to find a route starting and
ending at x1 that will take in all cities with the minimum cost.

Algorithm-

 Travelling salesman problem takes a graph G {V, E} as an input and declare another
graph as the output (say G’) which will record the path the salesman is going to take from
one node to another.
 The algorithm begins by sorting all the edges in the input graph G from the least distance
to the largest distance.
 The first edge selected is the edge with least distance, and one of the two vertices (say A
and B) being the origin node (say A).
 Then among the adjacent edges of the node other than the origin node (B), find the least
cost edge and add it onto the output graph.
 Continue the process with further nodes making sure there are no cycles in the output
graph and the path reaches back to the origin node A.
 If the origin is mentioned in the given problem, then the solution must always start from
that node only.

Fig 8.1: Travelling Sales Man Graph

Shubham A20405220146
Shubham A20405220146

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