0% found this document useful (0 votes)
27 views12 pages

Ai Outputs

The program uses a state space search algorithm to find a sequence of moves between the starting state and a goal state by defining the possible jug capacities and moves between states until the goal of having exactly 2 liters in one of the jugs is reached.

Uploaded by

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

Ai Outputs

The program uses a state space search algorithm to find a sequence of moves between the starting state and a goal state by defining the possible jug capacities and moves between states until the goal of having exactly 2 liters in one of the jugs is reached.

Uploaded by

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

Experiment No.

import random

# Initialize the 4x4 grid for the Wumpus World


grid = [['' for _ in range(4)] for _ in range(4)]

# Place the Wumpus at a random location


wumpus_location = (random.randint(0, 3), random.randint(0, 3))
grid[wumpus_location[0]][wumpus_location[1]] = 'W'

# Place the gold at a random location


gold_location = (random.randint(0, 3), random.randint(0, 3))
grid[gold_location[0]][gold_location[1]] = 'G'

# Place the pits at random locations


num_pits = 3
pit_locations = []
for _ in range(num_pits):
pit_location = (random.randint(0, 3), random.randint(0, 3))
while pit_location == wumpus_location or pit_location ==
gold_location or pit_location in pit_locations:
pit_location = (random.randint(0, 3), random.randint(0, 3))
pit_locations.append(pit_location)
grid[pit_location[0]][pit_location[1]] = 'P'

# Initialize user position


user_position = (0, 0)

# User movement
while True:
# Update the grid with the agent's current position
grid[user_position[0]][user_position[1]] = 'A'

print("Current Grid:")
for row in grid:
print(row)

move = input("Enter your move (up, down, left, right): ")

# Clear the agent's previous position


grid[user_position[0]][user_position[1]] = ''

if move == 'up' and user_position[0] > 0:


user_position = (user_position[0] - 1, user_position[1])
elif move == 'down' and user_position[0] < 3:
user_position = (user_position[0] + 1, user_position[1])
elif move == 'left' and user_position[1] > 0:
user_position = (user_position[0], user_position[1] - 1)
elif move == 'right' and user_position[1] < 3:
user_position = (user_position[0], user_position[1] + 1)
else:
print("Invalid move. Try again.")
continue

if user_position == gold_location:
print("Congratulations! You found the gold!")
break
if user_position == wumpus_location:
print("Game Over! You encountered the Wumpus.")
break

if user_position in pit_locations:
print("Game Over! You fell into a pit.")
break

**************OUTPUT**************

Current Grid:
['A', 'W', '', '']
['', '', 'G', '']
['', '', 'P', '']
['P', 'P', '', '']
Enter your move (up, down, left, right): down
Current Grid:
['', 'W', '', '']
['A', '', 'G', '']
['', '', 'P', '']
['P', 'P', '', '']
Enter your move (up, down, left, right): right
Current Grid:
['', 'W', '', '']
['', 'A', 'G', '']
['', '', 'P', '']
['P', 'P', '', '']
Enter your move (up, down, left, right): right
Congratulations! You found the gold!
Experiment No.3

from collections import deque

def bfs(graph, start, goal):


queue = deque([(start, [start])])

while queue:
node, path = queue.popleft()

print(f"Visited node {node} with path: {' -> '.join(path)}")

if node == goal:
return path

for neighbor in graph[node]:


if neighbor not in path:
new_path = path + [neighbor]
queue.append((neighbor, new_path))

return None

graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C']
}

start_node = 'A'
goal_node = 'F'
print(f"Starting BFS from node {start_node} to find node {goal_node}:")

path = bfs(graph, start_node, goal_node)

if path:
print(f"Shortest path from {start_node} to {goal_node}: {' ->
'.join(path)}")
else:
print(f"No path found from {start_node} to {goal_node}")

***************OUTPUT***************

Starting BFS from node A to find node F:


Visited node A with path: A
Visited node B with path: A -> B
Visited node C with path: A -> C
Visited node D with path: A -> B -> D
Visited node E with path: A -> B -> E
Visited node F with path: A -> C -> F
Shortest path from A to F: A -> C -> F
Experiment No.4

def dfs(graph, start, goal):


stack = [(start, [start])]
visited = set()
while stack:
current_node, path = stack.pop()
print("Visiting node:", current_node, "Path:", ' -> '.join(path))

if current_node == goal:
print("Goal node reached!")
return

visited.add(current_node)
for neighbor in reversed(graph[current_node]):
if neighbor not in visited and neighbor not in (node for
node, _ in stack):
stack.append((neighbor, path + [neighbor]))

print("Goal node not reachable!")

graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B'],
'F': ['C']
}

start_node = 'A'
goal_node = 'F'

print("Starting DFS from node:", start_node)


dfs(graph, start_node, goal_node)

**************OUTPUT**************

Starting DFS from node: A


Visiting node: A Path: A
Visiting node: B Path: A -> B
Visiting node: D Path: A -> B -> D
Visiting node: E Path: A -> B -> E
Visiting node: C Path: A -> C
Visiting node: F Path: A -> C -> F
Goal node reached!
Experiment No.5

import heapq

def heuristic(node, goal):


return abs(node[0] - goal[0]) + abs(node[1] - goal[1])

def astar(graph, start, goal):


open_set = [(0, start)]
g_score = {node: float('inf') for node in graph}
g_score[start] = 0
came_from = {}

while open_set:
current_f_score, current_node = heapq.heappop(open_set)

if current_node == goal:
path = []
while current_node in came_from:
path.append(current_node)
current_node = came_from[current_node]
path.append(start)
path.reverse()
return path

for neighbor, cost in graph[current_node]:


tentative_g_score = g_score[current_node] + cost
if tentative_g_score < g_score[neighbor]:
came_from[neighbor] = current_node
g_score[neighbor] = tentative_g_score
f_score = tentative_g_score + heuristic(neighbor, goal)
heapq.heappush(open_set, (f_score, neighbor))

return None

graph = {
(0, 0): [((0, 1), 1), ((1, 0), 1)],
(0, 1): [((0, 0), 1), ((1, 1), 1), ((2, 1), 2)],
(1, 0): [((0, 0), 1), ((1, 1), 1), ((1, 2), 2)],
(1, 1): [((0, 1), 1), ((1, 0), 1), ((1, 2), 1), ((2, 1), 1)],
(1, 2): [((1, 1), 1), ((2, 2), 2)],
(2, 1): [((1, 1), 1), ((1, 2), 1), ((2, 2), 1)],
(2, 2): [((1, 2), 2), ((2, 1), 1)]
}

start_node = (0, 0)
goal_node = (2, 2)

path = astar(graph, start_node, goal_node)

if path:
print("Optimal Path:", ' -> '.join(map(str, path)))
else:
print("Path not found")

**********OUTPUT************
Optimal Path: (0, 0) -> (0, 1) -> (2, 1) -> (2, 2)
Experiment No.6

import random

def print_board(board):
for i in range(0, 9, 3):
print(" | ".join(board[i:i+3]))

def check_winner(board, player):


winning_combinations = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
[0, 4, 8], [2, 4, 6] # Diagonals
]
for combo in winning_combinations:
if all(board[i] == player for i in combo):
return True
return False

def available_moves(board):
return [i for i, cell in enumerate(board) if cell == " "]

def ai_move(board):
return random.choice(available_moves(board))

def tic_tac_toe():
board = [" " for _ in range(9)]
players = ["X", "O"]
current_player = players[random.randint(0, 1)]

print("Let's play Tic Tac Toe!")


print_board(board)

while True:
print(f"Player {current_player}'s turn.")
if current_player == "X":
move = int(input("Enter cell number (1-9): ")) - 1
if board[move] != " ":
print("Cell already taken. Try again.")
continue
else:
move = ai_move(board)
board[move] = current_player
print_board(board)
if check_winner(board, current_player):
print(f"Player {current_player} wins!")
break
elif " " not in board:
print("It's a draw!")
break
current_player = players[(players.index(current_player) + 1) % 2]

tic_tac_toe()
*************OUTPUT************

Let's play Tic Tac Toe!


| |
| |
| |
Player X's turn.
Enter cell number (1-9): 5
| |
| X |
| |
Player O's turn.
| | O
| X |
| |
Player X's turn.
Enter cell number (1-9): 9
| | O
| X |
| | X
Player O's turn.
| | O
O | X |
| | X
Player X's turn.
Enter cell number (1-9): 1
X | | O
O | X |
| | X
Player X wins!
Experiment No.7

% Define the capacities of the two jugs and the goal amount.
capacity1(4). % Capacity of the first jug
capacity2(3). % Capacity of the second jug
goal(2). % Goal: One of the jugs should have exactly 2 liters of
water

% Check if the goal state is reached.


goal_state(state(X, _)) :- goal(G), X = G.
goal_state(state(_, Y)) :- goal(G), Y = G.

% Possible moves:
% 1. Fill Jug 1
move(state(_, Y), state(X2, Y), fill_jug1) :-
capacity1(X2),
X2 \= 0. % Avoid filling if the jug is already full.

% 2. Fill Jug 2
move(state(X, _), state(X, Y2), fill_jug2) :-
capacity2(Y2),
Y2 \= 0. % Avoid filling if the jug is already full.

% 3. Empty Jug 1
move(state(X, Y), state(0, Y), empty_jug1) :-
X > 0.

% 4. Empty Jug 2
move(state(X, Y), state(X, 0), empty_jug2) :-
Y > 0.

% 5. Pour water from Jug 1 to Jug 2


move(state(X, Y), state(X1, Y1), pour_jug1_to_jug2) :-
capacity2(YMax),
X > 0,
Y < YMax,
Transfer is min(X, YMax - Y),
X1 is X - Transfer,
Y1 is Y + Transfer,
Y1 \= Y. % Avoid pouring if no water is transferred.

% 6. Pour water from Jug 2 to Jug 1


move(state(X, Y), state(X1, Y1), pour_jug2_to_jug1) :-
capacity1(XMax),
Y > 0,
X < XMax,
Transfer is min(Y, XMax - X),
X1 is X + Transfer,
Y1 is Y - Transfer,
X1 \= X. % Avoid pouring if no water is transferred.

% Use Depth-First Search to explore states.


dfs(Path, State, [State|Path]) :-
goal_state(State).

dfs(Path, State, Solution) :-


move(State, NextState, _Action),
\+ member(NextState, Path), % Prevent revisiting visited
states
dfs([NextState|Path], NextState, Solution).

% Find a solution path from initial state


solve(Initial, Solution) :-
dfs([Initial], Initial, RevSolution),
reverse(RevSolution, Solution).

% Example query to run the program


% ?- solve(state(0, 0), Solution).

************OUTPUT************

compiling C:/Users/91908/Desktop/SEM-6/AI/programs/water_jug_problem.pl
for byte code...
C:/Users/91908/Desktop/SEM-6/AI/programs/water_jug_problem.pl compiled,
64 lines read - 5903 bytes written, 6 ms
| ?- solve(state(0, 0), Solution).

Solution =
[state(0,0),state(4,0),state(4,3),state(0,3),state(3,0),state(3,3),state(
4,2)] ?
Experiment No.8

class BlockWorldAgent:
def __init__(self, initial_state, goal_state):
self.initial_state = initial_state
self.goal_state = goal_state

def plan(self):
# Implement a planning algorithm here to generate a plan to reach
the goal state
plan = self.generate_plan()
return plan

def generate_plan(self):
# Implement a planning algorithm (e.g., STRIPS) to generate a
plan dynamically
# This is just a placeholder; replace it with your planning
algorithm
# For simplicity, let's return a simple plan to move each block
to its goal position
plan = []
for block, goal_location in self.goal_state.items():
current_location = self.initial_state[block]
if current_location != goal_location:
if goal_location == "on table":
plan.append(f"Move block {block} to the table")
else:
plan.append(f"Stack block {block} on top of block
{goal_location}")
return plan

# Define initial and goal states with 4-5 blocks


initial_state = {"A": "on table", "B": "on table", "C": "on table", "D":
"on E", "E": "on table"}
goal_state = {"A": "on table", "B": "on C", "C": "on D", "D": "on table",
"E": "on table"}

# Create a BlockWorldAgent instance


agent = BlockWorldAgent(initial_state, goal_state)

# Print the initial state


print("Initial State:")
for block, location in initial_state.items():
print(f"Block {block} is {location}")

# Print the goal state


print("\nGoal State:")
for block, location in goal_state.items():
print(f"Block {block} should be {location}")

# Generate and execute the plan


plan = agent.plan()
print("\nPlan to Achieve Goal State:")
for action in plan:
print(action)
*************OUTPUT**********

Initial State:
Block A is on table
Block B is on table
Block C is on table
Block D is on E
Block E is on table

Goal State:
Block A should be on table
Block B should be on C
Block C should be on D
Block D should be on table
Block E should be on table

Plan to Achieve Goal State:


Stack block B on top of block on C
Stack block C on top of block on D
Move block D to the table

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