Intel AI Mini Project
Intel AI Mini Project
2025
1. Write a Python program to solve the N-Queens problem using the Hill Climbing
algorithm
Sol:
import random
for i in range(n):
for j in range(i + 1, n):
# Check if queens are in the same column or diagonal
if board[i] == board[j] or abs(board[i] - board[j]) == j - i:
conflicts += 1
return conflicts
while True:
conflicts = calculate_conflicts(board)
for i in range(n):
for j in range(n):
if j != board[i]: # Don't move the queen to the same row
neighbor = board[:]
neighbor[i] = j
neighbors.append(neighbor)
# Evaluate neighbors by their conflict count
best_neighbor = None
min_conflicts = float('inf')
if solution is None:
print(f"No solution found for N={n}")
else:
print(f"Solution for N={n}:")
print_solution(solution)
# Example usage
n = 8 # Change N as needed
solve_n_queens(n)
Output:
2. Write a Python program to find the maximum of the function f(x) = -x² + 4x
using Hill Climbing.
Sol:
import random
for _ in range(max_iterations):
# Generate neighbors
next_x1 = current_x + step_size
next_x2 = current_x - step_size
# Evaluate neighbors
value1 = f(next_x1)
value2 = f(next_x2)
# Choose the best neighbor
if value1 > current_value:
current_x = next_x1
current_value = value1
elif value2 > current_value:
current_x = next_x2
current_value = value2
else:
# No better neighbor found
break
Output:
best_tour = current_tour[:]
best_cost = current_cost
# Cool down
temp *= cooling_rate
# Solve TSP
best_path, best_distance = simulated_annealing(cities)
# Print result
print("Best tour:", best_path)
print("Shortest distance:", round(best_distance, 2))
Output:
best_x = current_x
best_f = current_f
# Update best
if new_f > best_f:
best_x = new_x
best_f = new_f
# Cool down
temp *= cooling_rate
# Show result
print(f"Global maximum found at x = {best_x:.6f}")
print(f"Maximum value f(x) = {best_value:.6f}")
Output:
return transition_probs
next_states = list(transition_probs[today].keys())
probabilities = list(transition_probs[today].values())
# Build model
transition_probs = build_transition_matrix(historical_weather)
# Example usage
today_weather = input("Enter today's weather (Sunny, Cloudy, Rainy): ").capitalize()
Output:
6. Write a Python program to simulate a decision tree for making choices under
uncertainty using Decision Theory
Sol:
# Decision Tree Simulation using Decision Theory (Expected Value)
# Each decision has a list of outcomes with associated probability and reward
decisions = {
"Launch New Product": [
{"outcome": "High Market Demand", "probability": 0.3, "value": 100000},
{"outcome": "Moderate Market Demand", "probability": 0.5, "value": 40000},
{"outcome": "Low Market Demand", "probability": 0.2, "value": -20000}
],
"Improve Existing Product": [
{"outcome": "Increased Sales", "probability": 0.6, "value": 30000},
{"outcome": "No Significant Change", "probability": 0.4, "value": 5000}
]
}
def expected_value(outcomes):
"""Calculate expected value for a list of outcomes."""
return sum(o["probability"] * o["value"] for o in outcomes)
Output:
POP_SIZE = 50
GENS = 1000
MUTATION_RATE = 0.1
# Activation
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# Mutation
def mutate(chrom):
for i in range(CHROMOSOME_LENGTH):
if random.random() < MUTATION_RATE:
chrom[i] += random.uniform(-0.5, 0.5)
return chrom
# Genetic Algorithm
def genetic_algorithm():
population = [create_chromosome() for _ in range(POP_SIZE)]
for gen in range(GENS):
population = sorted(population, key=lambda chrom: fitness(chrom))
best_fit = fitness(population[0])
if gen % 100 == 0:
print(f"Generation {gen}, Best MSE: {best_fit:.5f}")
if best_fit < 0.01:
print(f"\nSolution found at generation {gen} with MSE: {best_fit:.5f}")
return population[0]
population = new_pop
Output:
8. Write a Python program to classify emails as spam or not spam using Support
Vector Machines (SVM).
Sol:
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, classification_report
Output:
9. Write a Python program to train a robot using Q-learning to reach a goal in a
grid world environment.
Sol:
import numpy as np
import random
# Parameters
alpha = 0.8 # Learning rate
gamma = 0.95 # Discount factor
epsilon = 0.1 # Exploration rate
episodes = 2000
max_steps = 50
def is_valid_pos(pos):
r, c = pos
return 0 <= r < GRID_SIZE and 0 <= c < GRID_SIZE
def get_next_state(state, action):
r, c = state
if action == 'up':
r -= 1
elif action == 'down':
r += 1
elif action == 'left':
c -= 1
elif action == 'right':
c += 1
return (r, c) if is_valid_pos((r, c)) else state
def get_reward(state):
if state == GOAL:
return 100 # Reward for reaching the goal
else:
return -1 # Small penalty for each move to encourage shortest path
action = actions[action_idx]
next_state = get_next_state(state, action)
reward = get_reward(next_state)
nr, nc = next_state
if state == GOAL:
break
Output:
10. Write a Python program to simulate LIDAR sensor data for obstacle detection
in a 2D map.
Sol:
import math
import numpy as np
import matplotlib.pyplot as plt
# LIDAR parameters
lidar_pos = (10, 5) # (x, y)
max_range = 15
num_rays = 360 # 1-degree resolution
Output: