Iai 16010422097 Exp6
Iai 16010422097 Exp6
Program/ Steps:
import heapq
import itertools
class PuzzleNode:
def __init__(self, state, cost, heuristic, parent=None,
action=None):
self.state = state
self.cost = cost
self.heuristic = heuristic
self.parent = parent
self.action = action
def get_legal_moves(state):
empty_index = state.index(0)
x, y = divmod(empty_index, 3)
moves = []
if x > 0:
moves.append(empty_index - 3) # Up
if x < 2:
moves.append(empty_index + 3) # Down
if y > 0:
moves.append(empty_index - 1) # Left
if y < 2:
moves.append(empty_index + 1) # Right
return moves
def get_next_states(state):
legal_moves = get_legal_moves(state)
next_states = []
for move in legal_moves:
next_state = list(state)
empty_index = state.index(0)
next_state[empty_index] = state[move]
next_state[move] = 0
next_states.append(next_state)
return next_states
while open_list:
current_node = heapq.heappop(open_list)
current_state = current_node.state
if current_state == goal_state:
# Reconstruct the path
path = []
while current_node:
path.append(current_node.state)
current_node = current_node.parent
path.reverse()
return path[1:], len(path) - 1 # Exclude initial
state and count number of moves
if tuple(current_state) in closed_list:
continue
closed_list.add(tuple(current_state))
return "impossible"
# Example usage:
initial_state = [5, 0, 8, 2, 1, 6, 7, 4, 3] # Example initial
state
goal_state = [1, 2, 3, 4, 5, 6, 7, 8, 0] # Example goal state
Output/Result:
Path:
[5, 0, 8]
[2, 1, 6]
[7, 4, 3]
[5, 1, 8]
[2, 0, 6]
[7, 4, 3]
[5, 1, 8]
[2, 4, 6]
[7, 0, 3]
[5, 1, 8]
[2, 4, 6]
[7, 3, 0]
[5, 1, 8]
[2, 4, 0]
[7, 3, 6]
[5, 1, 0]
[2, 4, 8]
[7, 3, 6]
[5, 0, 1]
[2, 4, 8]
[7, 3, 6]
[0, 5, 1]
[2, 4, 8]
[7, 3, 6]
[2, 5, 1]
[0, 4, 8]
[7, 3, 6]
[2, 5, 1]
[4, 0, 8]
[7, 3, 6]
[2, 5, 1]
[4, 3, 8]
[7, 0, 6]
[2, 5, 1]
[4, 3, 8]
[7, 6, 0]
[2, 5, 1]
[4, 3, 0]
[7, 6,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[7, 1, 5]
[6, 2, 0]
[3, 8, 4]
[7, 1, 0]
[6, 2, 5]
[3, 8, 4]
[7, 0, 1]
[6, 2, 5]
[3, 8, 4]
[7, 2, 1]
[6, 0, 5]
[3, 8, 4]
[7, 2, 1]
[6, 8, 5]
[3, 0, 4]
[7, 2, 1]
[6, 8, 5]
[0, 3, 4]
[7, 2, 1]
[0, 8, 5]
[6, 3, 4]
[0, 2, 1]
[7, 8, 5]
[6, 3, 4]
[2, 0, 1]
[7, 8, 5]
[6, 3, 4
Outcomes: Ability to formally state the problem and develop the appropriate proof for given a
logical deduction problem.
The aim of writing a Prolog program for the 8-Puzzle problem is to demonstrate the application
of logic programming in solving a classic problem in artificial intelligence and puzzle-solving.
By implementing the program, we can explore how Prolog's logical inference engine can
efficiently search through the puzzle state space to find a solution. Through this exercise, we
gain insights into the use of logic-based approaches for problem-solving and expand our
understanding of both Prolog programming and the 8-Puzzle problem itself.