0% found this document useful (0 votes)
17 views

PROGRAMS

The document contains two main sections: a Tic-Tac-Toe game implementation and a Hill Climbing algorithm example. The Tic-Tac-Toe section includes functions for printing the board, checking for a winner, and determining if the game is a draw, allowing two players to take turns. The Hill Climbing section describes an optimization algorithm that seeks to maximize a given objective function, demonstrating its execution with a random starting point.

Uploaded by

nagalallig
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)
17 views

PROGRAMS

The document contains two main sections: a Tic-Tac-Toe game implementation and a Hill Climbing algorithm example. The Tic-Tac-Toe section includes functions for printing the board, checking for a winner, and determining if the game is a draw, allowing two players to take turns. The Hill Climbing section describes an optimization algorithm that seeks to maximize a given objective function, demonstrating its execution with a random starting point.

Uploaded by

nagalallig
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/ 3

TICTOE GAME:

def print_board(board):
"""Prints the Tic-Tac-Toe board."""
for row in board:
print(" | ".join(row))
print("-" * 9)

def check_winner(board, player):


"""Checks if a player has won the game."""
# Check rows
for row in board:
if all(cell == player for cell in row):
return True

# Check columns
for col in range(3):
if all(board[row][col] == player for row in range(3)):
return True

# Check diagonals
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
return True

return False

def is_draw(board):
"""Checks if the game is a draw."""
return all(board[row][col] != " " for row in range(3) for col in range(3))

def tic_tac_toe():
"""Main function to run the Tic-Tac-Toe game."""
board = [[" " for _ in range(3)] for _ in range(3)]
players = ["X", "O"]
turn = 0

print("Welcome to Tic-Tac-Toe!")
print_board(board)

while True:
player = players[turn % 2]
print(f"Player {player}, it's your turn.")

while True:
try:
row, col = map(int, input("Enter row and column (0-2, separated by space): ").split())
if board[row][col] == " ":
board[row][col] = player
break
else:
print("That spot is already taken. Try again.")
except (ValueError, IndexError):
print("Invalid input. Enter row and column numbers between 0 and 2.")

print_board(board)

if check_winner(board, player):
print(f"🎉 Player {player} wins!")
break
elif is_draw(board):
print("It's a draw!")
break

turn += 1

# Run the game


tic_tac_toe()

Output:

Welcome to Tic-Tac-Toe!
| |
---------
| |
---------
| |
Player X, it's your turn.
Enter row and column (0-2, separated by space): 0 0
X| |
---------
| |
---------
| |
Player O, it's your turn.
Enter row and column (0-2, separated by space): 1 1
X| |
---------
|O|
---------
| |
HILL CLIMBING

import random

def objective_function(x):
"""Function to maximize: f(x) = -x² + 4x"""
return -x**2 + 4*x # Example function

def hill_climb(start_x, step_size=0.1, max_iterations=100):


"""Performs the Hill Climbing algorithm."""
current_x = start_x
current_value = objective_function(current_x)

for _ in range(max_iterations):
# Generate possible next step
next_x = current_x + random.choice([-step_size, step_size])
next_value = objective_function(next_x)

# Move if the next value is better


if next_value > current_value:
current_x, current_value = next_x, next_value
else:
break # Stop if no improvement

return current_x, current_value

# Run the Hill Climbing algorithm


start = random.uniform(0, 4) # Start from a random point in range [0, 4]
best_x, best_value = hill_climb(start)

print(f"Starting Point: {start:.2f}")


print(f"Optimal x: {best_x:.2f}, Maximum f(x): {best_value:.2f}")

OUTPUT

Starting Point: 2.45


Optimal x: 2.93, Maximum f(x): 3.46

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