0% found this document useful (0 votes)
20 views18 pages

8 Puzzle

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)
20 views18 pages

8 Puzzle

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

Write a program in prolog to solve 8 Puzzle problems

Aim: To Write a program in prolog to solve 8 Puzzle problems

Introduction:

Source Code:

ids :-

start(State),

length(Moves, N),

dfs([State], Moves, Path), !,

show([start|Moves], Path),

format('~nmoves = ~w~n', [N]).

dfs([State|States], [], Path) :-

goal(State), !,
reverse([State|States], Path).

dfs([State|States], [Move|Moves], Path) :-

move(State, Next, Move),

not(memberchk(Next, [State|States])),

dfs([Next,State|States], Moves, Path).

show([], _).

show([Move|Moves], [State|States]) :-

State = state(A,B,C,D,E,F,G,H,I),

format('~n~w~n~n', [Move]),

format('~w ~w ~w~n',[A,B,C]),

format('~w ~w ~w~n',[D,E,F]),

format('~w ~w ~w~n',[G,H,I]),

show(Moves, States).

% Empty position is marked with '*'

start( state(6,1,3,4,*,5,7,2,0) ).

goal( state(*,0,1,2,3,4,5,6,7) ).

move( state(*,B,C,D,E,F,G,H,J), state(B,*,C,D,E,F,G,H,J), right).

move( state(*,B,C,D,E,F,G,H,J), state(D,B,C,*,E,F,G,H,J), down ).

move( state(A,*,C,D,E,F,G,H,J), state(*,A,C,D,E,F,G,H,J), left ).


move( state(A,*,C,D,E,F,G,H,J), state(A,C,*,D,E,F,G,H,J), right).

move( state(A,*,C,D,E,F,G,H,J), state(A,E,C,D,*,F,G,H,J), down ).

move( state(A,B,*,D,E,F,G,H,J), state(A,*,B,D,E,F,G,H,J), left ).

move( state(A,B,*,D,E,F,G,H,J), state(A,B,F,D,E,*,G,H,J), down ).

move( state(A,B,C,*,E,F,G,H,J), state(*,B,C,A,E,F,G,H,J), up ).

move( state(A,B,C,*,E,F,G,H,J), state(A,B,C,E,*,F,G,H,J), right).

move( state(A,B,C,*,E,F,G,H,J), state(A,B,C,G,E,F,*,H,J), down ).

move( state(A,B,C,D,*,F,G,H,J), state(A,*,C,D,B,F,G,H,J), up ).

move( state(A,B,C,D,*,F,G,H,J), state(A,B,C,D,F,*,G,H,J), right).

move( state(A,B,C,D,*,F,G,H,J), state(A,B,C,D,H,F,G,*,J), down ).

move( state(A,B,C,D,*,F,G,H,J), state(A,B,C,*,D,F,G,H,J), left ).

move( state(A,B,C,D,E,*,G,H,J), state(A,B,*,D,E,C,G,H,J), up ).

move( state(A,B,C,D,E,*,G,H,J), state(A,B,C,D,*,E,G,H,J), left ).

move( state(A,B,C,D,E,*,G,H,J), state(A,B,C,D,E,J,G,H,*), down ).

move( state(A,B,C,D,E,F,*,H,J), state(A,B,C,D,E,F,H,*,J), left ).

move( state(A,B,C,D,E,F,*,H,J), state(A,B,C,*,E,F,D,H,J), up ).

move( state(A,B,C,D,E,F,G,*,J), state(A,B,C,D,E,F,*,G,J), left ).

move( state(A,B,C,D,E,F,G,*,J), state(A,B,C,D,*,F,G,E,J), up ).

move( state(A,B,C,D,E,F,G,*,J), state(A,B,C,D,E,F,G,J,*), right).

move( state(A,B,C,D,E,F,G,H,*), state(A,B,C,D,E,*,G,H,F), up ).

move( state(A,B,C,D,E,F,G,H,*), state(A,B,C,D,E,F,G,*,H), left ).

Output:

Time(ids)
Write a python program to implement Breadth First Search Traversal?

Aim: To Write a python program to implement Breadth First Search Traversal

Introduction:

Breadth-first search (BFS) is an algorithm for traversing graphs or trees. Breath-first searches for
trees and graphs are almost the same. The only difference is that the graph may contain cycles,
so we may traverse to the same node again. To avoid processing the same node again, we use the
boolean visited array, which will mark the visited vertices. BFS uses a queue data structure for
finding the shortest path in a graph.

Breadth-First Search Python Algorithm

The breadth-first search algorithm uses a queue and a visited array. We use the queue to get the
next vertex to start the search, and the visited array is used to mark all the nodes that have been
visited, so when it appears again, we will perform BFS on that node.

The algorithm works as follows:

 Create a queue and insert any one vertex of the graph at the back of the queue.
 Initialize a visited array and mark that vertex as visited.
 Follow the below process till the queue becomes empty:
o Remove a front vertex from the queue.
o Get all the adjacent vertices of the removed vertex.
o If the adjacent vertex has not been visited, mark it as visited and insert it at the
back of the queue.

Breadth First Search Algorithm Work with an Example

Let’s have a look at the algorithm with an example. Here we have an undirected graph of 5
vertices.

Initialize the queue.


Start from node A and mark it as visited.

Now, we can see that there are 3 neighbors of node A that are unvisited, so alphabetically we
use node B and mark it as visited, and add it to the queue.

Next, the unvisited node is C, so mark it as visited and add it to the queue.
Now, the node D remains, so mark it as visited and add it to the queue.

Now, node A is left with no unvisited nodes, so start removing nodes from the queue. So node B
pops from the queue, and since B has only one neighbor, i.e., A, and it has already been visited,
we move forward and pop the next node from the queue.

Node C is removed from the queue. C has two neighbors: A and D. They have already been
visited.
Now, only D remains in the queue, so pop it from the queue and mark all its neighbors visited.
So D has 3 neighbors: A, C, and E. But only E is not visited, so mark E as visited and add E to
the queue.

At last, pop E from the queue, and mark it as visited, since E has only one neighbor, i.e., D, but it
has already been visited. So our queue will become empty.

Now, our queue becomes empty, so we have completed the breadth-first search traversal of the
graph.

Source code:
# Create a graph given in the above diagram.

graph = {

'A': ['B', 'C', 'D'],

'B': ['A'],

'C': ['A', 'D'],

'D': ['A', 'C', 'E'],

'E': ['D'],

# to print a BFS of a graph

def bfs(node):

# mark vertices as False means not visited

visited = [False] * (len(graph))

# make an empty queue for bfs

queue = []

# mark gave node as visited and add it to the queue

visited.append(node)

queue.append(node)

while queue:

# Remove the front vertex or the vertex at the 0th index from the queue and print that vertex.

v = queue.pop(0)
print(v, end=" ")

# Get all adjacent nodes of the removed node v from the graph hash table.

# If an adjacent node has not been visited yet,

# then mark it as visited and add it to the queue.

for neigh in graph[v]:

if neigh not in visited:

visited.append(neigh)

queue.append(neigh)

# Driver Code

if __name__ == "__main__":

bfs('A')
Write a python program to implement Depth First Search Traversal?

Aim: To Write a python program to implement Depth First Search Traversal?

Introduction:

Depth-first search (DFS), is an algorithm for tree traversal on graph or tree data structures. It
can be implemented easily using recursion and data structures like dictionaries and sets.

The Algorithm

1. Pick any node. If it is unvisited, mark it as visited and recur on all its adjacent nodes.
2. Repeat until all the nodes are visited, or the node to be searched is found.

Implementation

Consider this graph, implemented in the code below:

Source code:
# Using a Python dictionary to act as an adjacency list
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited = set() # Set to keep track of visited nodes.

def dfs(visited, graph, node):


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
dfs(visited, graph, 'A')
Write a python program to implement Water Jug Problem

Aim: To Write a python program to implement Water Jug Problem


Water Jug Problem
Here is the problem statement for Water Jug Problem:
You are given 2 jugs with the capacity 'm' and 'n' respectively. Initially, they are given empty.
There is an unlimited supply of water. You can either fill the whole jug or a quantity that is less
than the given capacity of jugs. Now, you are also given a third positive integer 'd'. Using the 2
given jugs, you need to come up with a solution to have 'd' amount of water in them and return
the number of steps you took to reach that capacity.

Understanding the Problem


Before beginning the coding part, it is very important for you to understand what the question is
asking you to do. Many students just copy the code from web servers and later, when the
interviewer asks any question from it, they are stuck and even embarrassed. So, to save yourself
from such questions, kindly go through this section carefully.
So, you are given 2 jugs with their capacities. It has also been clearly stated in the question that
with the unlimited water supply, you can either fill the whole jug up to its capacity or somewhat
less than that. Keep that in mind.
Secondly, we need to find a way to somehow have a 'd' amount of water left in the jugs.
Basically, we need to transfer, fill and, empty the jugs to get the required capacity of water in the
jugs.
The next most important question is which data structure should you choose for this question.
You cannot use arrays as it will be a heavy task for both the compiler(in terms of time and
auxiliary space complexity) and you(in terms of long codes).
You should choose a structure with which you can manage the content of both jugs
simultaneously on the front. The possible and safest option is to use Sets or Pairs.
How to Approach the Solution?
Now that we have chosen what to work with, let's understand how you can actually make it
work. Well, for starters you can have (a, b) which represents the amount of water currently in jug
1 and jug 2 respectively. Initially, both the components will be (0, 0) since the jugs are empty in
the beginning. The final state of the jugs will be either (0, d) or (d, 0) as both add up to give a
total of the required quantity.
The following operations can be performed on the jugs:

1. Empty a jug (a, b) -> (0, b)


2. Fill a jug (0, b) -> (a, b)
3. Transfer water from one jug to another.

Example
Input: 3, 5, 4
Output: 6
Explanation: The following steps are taken:

1. Fill the 5-liter jug completely.


2. Transfer 3 liters from a 5-liter jug to a 3-liter jug.
3. Empty the 3-liter capacity jug.
4. Transfer the remaining 2 liters from a 5-liter jug to a 3-liter jug.
5. Now, fill the 5-liter jug fully.
6. Pour 1 liter from a 5-liter jug into a 3-liter jug.
7. There! We have 4 liters in the first jug, now empty the 2nd jug.

For more clarity, check the below illustration.


3 Methods to Solve the Water Jug Problem
Now, you know what the problem is and what is the approach behind the solution. Next, discuss
some methods with which you can code this problem. Following are the three methods, you can
use:
Method 01) Always pour from 1st jug to 2nd jug

1. Fill the m liter jug and empty it into the n liter jug.
2. When the m liter jug becomes empty refill it.
3. When the n-liter jug becomes full, empty it.
4. Repeat the above steps till any one of the jugs contains the required amount of water in
them.
Method 02) Always pour from 2nd jug to 1st jug

1. Fill the n-liter jug and empty it into the m-liter jug.
2. When the n liter jug becomes empty refill it.
3. When the m liter jug becomes full, empty it.
4. Repeat the above steps till any of the jugs contain the required amount of water in them.
Source code:
from collections import deque
def Solution(a, b, target):
m = {}
isSolvable = False
path = []

q = deque()

#Initializing with jugs being empty


q.append((0, 0))

while (len(q) > 0):

# Current state
u = q.popleft()
if ((u[0], u[1]) in m):
continue
if ((u[0] > a or u[1] > b or
u[0] < 0 or u[1] < 0)):
continue
path.append([u[0], u[1]])

m[(u[0], u[1])] = 1

if (u[0] == target or u[1] == target):


isSolvable = True

if (u[0] == target):
if (u[1] != 0):
path.append([u[0], 0])
else:
if (u[0] != 0):

path.append([0, u[1]])

sz = len(path)
for i in range(sz):
print("(", path[i][0], ",",
path[i][1], ")")
break

q.append([u[0], b]) # Fill Jug2


q.append([a, u[1]]) # Fill Jug1

for ap in range(max(a, b) + 1):


c = u[0] + ap
d = u[1] - ap

if (c == a or (d == 0 and d >= 0)):


q.append([c, d])

c = u[0] - ap
d = u[1] + ap

if ((c == 0 and c >= 0) or d == b):


q.append([c, d])

q.append([a, 0])

q.append([0, b])

if (not isSolvable):
print("Solution not possible")

if __name__ == '__main__':

Jug1, Jug2, target = 4, 3, 2


print("Path from initial state "
"to solution state ::")

Solution(Jug1, Jug2, target)

Write a program to implement Tic-Tac-Toe game using python

AIM: To Write a program to implement Tic-Tac-Toe game using python.

Introduction

In this article, I am showing you how to create a very simple game of Tic-Tac-Toe in Python.

Tic-Tac-Toe is a very simple two-player game. So only two players can play at a time. This
game is also known as Noughts and Crosses or Xs and Os game. One player plays with X, and
the other player plays with O. In this game, we have a board consisting of a 3X3 grid. The
number of grids may be increased.

The Tic-Tac-Toe board looks like the following


Rules of Game
1. Traditionally the first player plays with "X". So you can decide who wants to go with "X"
and who wants to go with "O".
2. Only one player can play at a time.
3. If any of the players have filled a square, then the other player and the same player cannot
override that square.
4. There are only two conditions that may match will be a draw or may win.
5. The player who succeeds in placing three respective marks (X or O) in a horizontal, vertical,
or diagonal row wins the game.
Condition for wiining

Whoever places three respective marks (X or O) horizontally, vertically, or diagonally will be the
winner.

Source Code:
import os
import time

board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player = 1

# Win Flags
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 Designed By Sourabh Somani")


print("Player 1 [X] --- Player 2 [O]\n")
print()
print()
print("Please Wait...")
time.sleep(3)

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

You might also like