Experiment Numbe1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Experiment Number: 3

Problem Statement: Simple Hill Climbing.

NAME: Sayyed Md Muaz Aslam ROLLNO: 60


CLASS: TY IT-A BATCH: B3

Code:

import copy

# Simple Hill Climbing for 8 puzzle problem

# To calculate number of misplaced tiles (Heuristic Value)


def num_misplaced_tiles(state, goal_state):
misplaced_num = []
for a, b in zip(state, goal_state):
for x, y in zip(a, b):
if x != y:
misplaced_num.append(1)
return sum(misplaced_num)

# To get list of possible next states for current state


def get_next_states(state):
moves = [(0, 1), (0, -1), (1, 0), (-1, 0)]
zero_row, zero_col = next((i, j) for i, row in enumerate(state) for
j, val in enumerate(row) if val == 0)
next_states = []
for move in moves:
new_row, new_col = zero_row + move[0], zero_col + move[1]
if 0 <= new_row < 3 and 0 <= new_col < 3:
new_state = copy.deepcopy(state)
new_state[zero_row][zero_col], new_state[new_row][new_col]
= new_state[new_row][new_col], new_state[zero_row][zero_col]
next_states.append(new_state)
return next_states

a=0

# Calculate f value
def calculate_f(state, goal_state):
return a + num_misplaced_tiles(state, goal_state)

# initial_state = [
# [2,8,3],
# [1,6,4],
# [7,0,5]
# ]
# goal_state = [
# [1,2,3],
# [8,0,4],
# [7,6,5]
# ]

initial_state = []
print("Enter initial state:")
for _ in range(3):
row = list(map(int, input().split()))
initial_state.append(row)

# Take input of goal state from the user


goal_state = []
print("Enter goal state:")
for _ in range(3):
row = list(map(int, input().split()))
goal_state.append(row)

print("Initial State:")
[print(row) for row in initial_state]
initial_f = calculate_f(initial_state, goal_state)
print("f(x) =", initial_f)
a=a+1

next_states = get_next_states(initial_state)

def calculate_f_for_key(state):
return calculate_f(state, goal_state)

best_state = min(next_states, key=calculate_f_for_key) # stores the


best state for the current state

best_f = calculate_f(best_state, goal_state) # f_val for best sate

print("\nBest Next State:")


[print(row) for row in best_state]
print("f(x) of Best Next State:", best_f)

if best_f < initial_f:


print()
else:
print("No better state found.")

Output:
Enter initial state:
102
356
748
Enter goal state:
123
456
789
Initial State:
[1, 0, 2]
[3, 5, 6]
[7, 4, 8]
f(x) = 5

Best Next State:


[1, 2, 0]
[3, 5, 6]
[7, 4, 8]
f(x) of Best Next State: 5
No better state found.

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