AI Lab Manual (2)
AI Lab Manual (2)
COURSE OBJECTIVES:
To design and implement different techniques to develop simple autonomous agents that
make effective decisions in fully informed, and partially observable, settings.
To apply appropriate algorithms for solving given AI problems.
To Design and implement logical reasoning agents.
To Design and implement agents that can reason under uncertainty.
To understand the Implementation of these reasoning systems using either backward or
forward inference mechanisms
LIST OF EXPERIMENTS:
COURSE OUTCOMES:
SOFTWARE:
Java
INDEX
Aim:
To develop PEAS description for the following AI tasks
(a) Automated Taxi Driving
(b) Vacuum Cleaner Agent
(c) Medical Diagnosis System
Algorithm:
3
Program :
import java.io.*;
import java.util.*;
class PEAS
{
public static void main(String args[])throws IOException
{
int choice;
Scanner sc= new Scanner(System.in);
System.out.println(" **** PEAS DESCRIPTION ****\n ------------------------- ");
System.out.println("\n 1. Automated Taxi Driving\n 2. Vacuum cleaner \n 3. Medical Diagnosis
System");
System.out.println("Enter your choice:");
choice= sc.nextInt();
switch(choice)
{
case 1:
{
System.out.println("Performance : Safety, Comfort, Affordable");
System.out.println("Environment : Road, Signals, Pedastrian Cross, other vehicles");
System.out.println("Actuators : Steering, breaking, acceleration");
System.out.println("Sensors : Accelerometer, Speedometer,Front lights,cameras");
break;
}
case 2:
{
System.out.println("Performance: Cleanness, efficiency: distance travelled to clean, battery life,
security");
System.out.println("Environment: Room, table, wood floor, carpet, different obstacles");
System.out.println("Actuators: Wheels, different brushes, vacuum extractor");
System.out.println("Sensors: Camera, dirt detection sensor, cliff sensor, bump sensors, infrared
wall sensors");
break;
}
case 3:
{
System.out.println("Performance: Healthy and Minimize Cost");
System.out.println("Environment: Patient, Hospital and Staff");
System.out.println("Actuators: Display, Questions, Test, Treatment ");
System.out.println("Sensors: Keyboard Entry, Symptoms, Patient's Answer");
break;
}
default:
{
System.out.println("Enter the right choice");
break;
}}}}
4
Output:
5
Result:
Thus, the program is executed successfully and the output is verified.
6
Ex.No 2a (Uninformed Search) Breadth First Search
Aim:
Graph
1 3
0 5
2 4
Algorithm
Graph Representation
Step 1: The graph is stored as an adjacency list using an ArrayList of ArrayLists for
each vertex.
BFS Algorithm:
Step 1: Use a queue to explore nodes level by level, which is the core of BFS.
Step 4: A visited array ensures that each node is only processed once.
Step 1: If the goal node is found during BFS traversal, the method returns true,
indicating success.
Step 2: If the BFS completes without finding the goal node, it returns false.
7
Program
import java.util.*;
E:\>java Graph
Visiting node: 0
Visiting node: 1
Visiting node: 2
Visiting node: 3
Visiting node: 4
Visiting node: 5
Goal node found: 5
Goal node 5 was found in the graph.
Result:
Thus, BFS implementation was done successfully for the given graph and the output is
verified.
10
Ex.No 2a (Uninformed Search) Depth First Search
Aim:
Graph
1 3
0 5
2 4
Algorithm
Graph Representation:
Step 1: The graph is represented as an adjacency list using
ArrayList<ArrayList<Integer>>.
Step 2: Each vertex has a list of adjacent vertices (neighbors).
DFS Algorithm:
Step 1: Use a recursive approach to implement DFS.
Step 2: The function dfsRecursive takes the current node and goal node as input,
marks the current node as visited, and explores all its neighbors.
Step 3: If a neighbor has not been visited, we recursively call DFS on that neighbor.
Step 4: If we reach the goal node during the recursion, we return true, otherwise, if
the DFS completes and the goal node isn't found, we return false.
11
Program
import java.util.ArrayList;
// If DFS completes and the goal node is not found, return false
return false;
}
13
Output
E:\>javac Graphdfs.java
E:\>java Graphdfs
Visiting node: 0
Visiting node: 1
Visiting node: 3
Visiting node: 5
Goal node found: 5
Goal node 5 was found in the graph.
Result:
Thus, DFS implementation was done successfully for the given graph and the output is
verified.
14
Ex.No. 3 Implement A* Algorithm in Traveling Salesman Problem
Aim:
To implement TSP for the following graph using A* algorithm.
Algorithm:
A* Algorithm:
Step 2: Check if the OPEN list is empty or not, if the list is empty then return failure and stops.
Step 3: Select the node from the OPEN list which has the smallest value of evaluation function
(g+h), if node n is goal node then return success and stop, otherwise
Step 4: Expand node n and generate all of its successors, and put n into the closed list. For each
successor n', check whether n' is already in the OPEN or CLOSED list, if not then compute
evaluation function for n' and place into Open list.
Step 5: Else if node n' is already in OPEN and CLOSED, then it should be attached to the back
pointer which reflects the lowest g(n') value.
Step1: Consider city n as the starting and ending point. Since route is cyclic, we can consider
any point as starting point.
Step3: Calculate cost of every permutation and keep track of minimum cost permutation.
15
Program:
import java.util.*;
import java.text.*;
class TSP
{
int weight[][],n,tour[],finalCost;
final int INF=1000;
public TSP()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no. of nodes:=>");
n=s.nextInt();
weight=new int[n][n];
tour=new int[n-1];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
System.out.print("Enter weight of "+(i+1)+" to "+(j+1)+":=>");
weight[i][j]=s.nextInt();
}
}
}
System.out.println();
System.out.println("Starting node assumed to be node1.");
eval();
}
public int COST(int currentNode,int inputSet[],int setSize)
{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
int setToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setSize;i++)
{
int k=0;
//initialise new set
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
minindex=inputSet[i];
16
}
}
return min;
}
public int MIN(int currentNode,int inputSet[],int setSize)
{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
int setToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setSize;i++)
//considers each node of inputSet
{
int k=0;
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
minindex=inputSet[i];
}
}
return minindex;
}
public void eval()
{
int dummySet[]=new int[n-1];
for(int i=1;i<n;i++)
dummySet[i-1]=i;
finalCost=COST(0,dummySet,n-1);
constructTour();
}
public void constructTour()
{
int previousSet[]=new int[n-1];
int nextSet[]=new int[n-2];
for(int i=1;i<n;i++)
previousSet[i-1]=i;
int setSize=n-1;
tour[0]=MIN(0,previousSet,setSize);
for(int i=1;i<n-1;i++)
{
int k=0;
for(int j=0;j<setSize;j++)
{
17
if(tour[i-1]!=previousSet[j])
nextSet[k++]=previousSet[j];
}
--setSize;
tour[i]=MIN(tour[i-1],nextSet,setSize);
for(int j=0;j<setSize;j++)
previousSet[j]=nextSet[j];
}
display();
}
public void display()
{
System.out.println();
System.out.print("The tour is 1-");
for(int i=0;i<n-1;i++)
System.out.print((tour[i]+1)+"-");
System.out.print("1");
System.out.println();
System.out.println("The final cost is "+finalCost);
}
}
class TSPExp
{
public static void main(String args[])
{
TSP obj=new TSP();
}
}
18
Output:
19
Result:
Thus, the Traveling Salesman Problem can be solved with the help of A* algorithm and
the output is verified.
20
Ex.No. 4 Implement Genetic Algorithms for AI tasks
Aim:
To implement simple Genetic Algorithm.
Algorithm:
21
Program:
import java.util.Random;
//Main class
public class GeneAlgo {
Population population = new Population();
Individual fittest;
Individual secondFittest;
int generationCount = 0;
public static void main(String[] args) {
Random rn = new Random();
SimpleDemoGA demo = new SimpleDemoGA();
//Initialize population
demo.population.initializePopulation(10);
22
//Select the most fittest individual
fittest = population.getFittest();
//Select the second most fittest individual
secondFittest = population.getSecondFittest();
}
//Crossover
void crossover() {
Random rn = new Random();
//Select a random crossover point
int crossOverPoint = rn.nextInt(population.individuals[0].geneLength);
//Swap values among parents
for (int i = 0; i < crossOverPoint; i++) {
int temp = fittest.genes[i];
fittest.genes[i] = secondFittest.genes[i];
secondFittest.genes[i] = temp;
}
}
//Mutation
void mutation() {
Random rn = new Random();
//Select a random mutation point
int mutationPoint = rn.nextInt(population.individuals[0].geneLength);
//Flip values at the mutation point
if (fittest.genes[mutationPoint] == 0) {
fittest.genes[mutationPoint] = 1;
} else {
fittest.genes[mutationPoint] = 0;
}
mutationPoint = rn.nextInt(population.individuals[0].geneLength);
if (secondFittest.genes[mutationPoint] == 0) {
secondFittest.genes[mutationPoint] = 1;
} else {
secondFittest.genes[mutationPoint] = 0;
}
}
//Get fittest offspring
Individual getFittestOffspring() {
if (fittest.fitness > secondFittest.fitness) {
return fittest;
}
return secondFittest;
}
//Replace least fittest individual from most fittest offspring
void addFittestOffspring() {
23
//Update fitness values of offspring
fittest.calcFitness();
secondFittest.calcFitness();
//Get index of least fit individual
int leastFittestIndex = population.getLeastFittestIndex();
//Replace least fittest individual from most fittest offspring
population.individuals[leastFittestIndex] = getFittestOffspring();
}
}
//Individual class
class Individual {
int fitness = 0;
int[] genes = new int[5];
int geneLength = 5;
public Individual() {
Random rn = new Random();
//Set genes randomly for each individual
for (int i = 0; i < genes.length; i++) {
genes[i] = Math.abs(rn.nextInt() % 2);
}
fitness = 0;
}
//Calculate fitness
public void calcFitness() {
fitness = 0;
for (int i = 0; i < 5; i++) {
if (genes[i] == 1) {
++fitness;
}
}
}
}
//Population class
class Population {
int popSize = 10;
Individual[] individuals = new Individual[10];
int fittest = 0;
//Initialize population
public void initializePopulation(int size) {
for (int i = 0; i < individuals.length; i++) {
individuals[i] = new Individual();
}
}
//Get the fittest individual
24
public Individual getFittest() {
int maxFit = Integer.MIN_VALUE;
int maxFitIndex = 0;
for (int i = 0; i < individuals.length; i++) {
if (maxFit <= individuals[i].fitness) {
maxFit = individuals[i].fitness;
maxFitIndex = i;
}
}
fittest = individuals[maxFitIndex].fitness;
return individuals[maxFitIndex];
}
//Get the second most fittest individual
public Individual getSecondFittest() {
int maxFit1 = 0;
int maxFit2 = 0;
for (int i = 0; i < individuals.length; i++) {
if (individuals[i].fitness > individuals[maxFit1].fitness) {
maxFit2 = maxFit1;
maxFit1 = i;
} else if (individuals[i].fitness > individuals[maxFit2].fitness) {
maxFit2 = i;
}
}
return individuals[maxFit2];
}
//Get index of least fittest individual
public int getLeastFittestIndex() {
int minFitVal = Integer.MAX_VALUE;
int minFitIndex = 0;
for (int i = 0; i < individuals.length; i++) {
if (minFitVal >= individuals[i].fitness) {
minFitVal = individuals[i].fitness;
minFitIndex = i;
}
}
return minFitIndex;
}
//Calculate fitness of each individual
public void calculateFitness() {
for (int i = 0; i < individuals.length; i++) {
individuals[i].calcFitness();
}
getFittest();}}
25
Output:
Generation: 0 Fittest: 4
Generation: 1 Fittest: 3
Generation: 2 Fittest: 3
Generation: 3 Fittest: 4
Generation: 4 Fittest: 4
Generation: 5 Fittest: 4
Generation: 6 Fittest: 3
Generation: 7 Fittest: 3
Generation: 8 Fittest: 5
26
Result:
Thus, the genetic algorithms implemented successfully and the output is verified.
27
Ex.No.5 Implementation of Traveling Salesman Problem using Simulated Annealing
Algorithms
Aim:
To implement TSP for finding shortest distance between two cities using Simulated
Annealing algorithms.
Algorithm:
Simulated Annealing
Step1: Generating an initial solution x0;
Step2: xbest ← x0;
Step3: Computing the value of the objective function f(x0) and f(xb est);
Step4: Ti ← T0;
Step5: while Ti>Tmin do
Step6: ∆f ← f(xnew)−f(xbest);
Step7: if ∆f < 0 then
Step8: xbest ← xnew;
Step9: end if
Step10: if ∆f ≥ 0 then
Step11: p ← e ∆f T ;
Step12: if c ← random[0, 1] ≥ p then
Step13: xbest ← xnew;
Step14: else
Step15: xbest ← xbest;
Step16: end if
Step17: end if
Step18: i ← i + 1;
Step19: Ti ← ρ × Ti ;
Step20: end while
Step21: Return xbest;
28
Algorithm :
City.java
Step1: Create a java file for city
Step2: With the help of this operator, initialize a random number
Step3: Get the X and Y coordinate of the city
Step4: Calculate the distance of X and Y coordinate of the city
Step5: Calculate the distance by using the following formula:
distance = sqrt ((xdistance2) – (ydistance)2)
Step6: Get the result.
Algorithm:
TourManager.java
Step1: Create a java file for TourManager
Step2: Create an object to store the names of various cities.
Step3: Add the destination cities
Step4: Get a city to calculate the distance.
Step5: Get the destination city
Algorithm:
Tour.java
Step1: Create a java file for tour
Step2: Get the tour of cities of a person
Step3: Construct a tour for a person
Step4: Get the city
Step5: Calculate the tour distance between the cities.
Algorithm:
SimulatedAnnealing.java
Step1: Create the main file for TSP
Step2: Calculate the acceptance probability
Step3: If the new solution is better, accept it otherwise, calculate an acceptance probability
Step4: Create and add our cities
Step5: Set the initial temperature as solution
Step6: Set as current best and Loop until system has cooled
Step7: Get a random position in the tour
Step8: Choose the best solution
29
Program:
city.java
package sa;
public class City {
int x;
int y;
// Constructs a randomly placed city
public City(){
this.x = (int)(Math.random()*200);
this.y = (int)(Math.random()*200);
}
// Constructs a city at chosen x, y location
public City(int x, int y){
this.x = x;
this.y = y;
}
// Gets city's x coordinate
public int getX(){
return this.x;
}
// Gets city's y coordinate
public int getY(){
return this.y;
}
// Gets the distance to given city
public double distanceTo(City city){
int xDistance = Math.abs(getX() - city.getX());
int yDistance = Math.abs(getY() - city.getY());
double distance = Math.sqrt( (xDistance*xDistance) + (yDistance*yDistance) );
return distance;
}
@Override
public String toString(){
return getX()+", "+getY();
}
}
TourManager.java
/*
* TourManager.java
* Holds the cities of a tour
*/
package sa;
import java.util.ArrayList;
public class TourManager {
// Holds our cities
30
private static ArrayList destinationCities = new ArrayList<City>();
// Adds a destination city
public static void addCity(City city) {
destinationCities.add(city);
}
// Get a city
public static City getCity(int index){
return (city)destinationCities.get(index);
}
// Get the number of destination cities
public static int numberOfCities(){
return destinationCities.size();
}
}
Tour.java
/*
* Tour.java
* Stores a candidate tour through all cities
*/
package sa;
import java.util.ArrayList;
import java.util.Collections;
public class Tour{
// Holds our tour of cities
private ArrayList tour = new ArrayList<City>();
// Cache
private int distance = 0;
// Constructs a blank tour
public Tour(){
for (int i = 0;i<TourManager.numberOfCities();i++) {
tour.add(null);
}
}
// Constructs a tour from another tour
public Tour(ArrayList tour){
this.tour = (ArrayList) tour.clone();
}
// Returns tour information
public ArrayList getTour(){
return tour;
}
// Creates a random individual
public void generateIndividual() {
// Loop through all our destination cities and add them to our tour
for (int cityIndex = 0; cityIndex < TourManager.numberOfCities(); cityIndex++) {
setCity(cityIndex, TourManager.getCity(cityIndex));
}
// Randomly reorder the tour
Collections.shuffle(tour);
31
}
// Gets a city from the tour
public City getCity(int tourPosition) {
return (City)tour.get(tourPosition);
}
// Sets a city in a certain position within a tour
public void setCity(int tourPosition, City city) {
tour.set(tourPosition, city);
// If the tours been altered we need to reset the fitness and distance
distance = 0;
}
// Gets the total distance of the tour
public int getDistance(){
if (distance == 0) {
int tourDistance = 0;
// Loop through our tour's cities
for (int cityIndex=0; cityIndex < tourSize(); cityIndex++) {
// Get city we're traveling from
City fromCity = getCity(cityIndex);
// City we're traveling to
City destinationCity;
// Check we're not on our tour's last city, if we are set our
// tour's final destination city to our starting city
if(cityIndex+1 < tourSize()){
destinationCity = getCity(cityIndex+1);
}
else{
destinationCity = getCity(0);
}
// Get the distance between the two cities
tourDistance += fromCity.distanceTo(destinationCity);
}
distance = tourDistance;
}
return distance;
}
// Get number of cities on our tour
public int tourSize() {
return tour.size();
}
@Override
public String toString() {
String geneString = "|";
for (int i = 0; i < tourSize(); i++) {
geneString += getCity(i)+"|";
}
return geneString;
}
}
32
SimulatedAnnealing.java
package sa;
public class SimulatedAnnealing {
// Calculate the acceptance probability
public static double acceptanceProbability(int energy, int newEnergy, double temperature) {
// If the new solution is better, accept it
if (newEnergy < energy) {
return 1.0;
}
// If the new solution is worse, calculate an acceptance probability
return Math.exp((energy - newEnergy) / temperature);
}
public static void main(String[] args) {
// Create and add our cities
City city = new City(60, 200);
TourManager.addCity(city);
City city2 = new City(180, 200);
TourManager.addCity(city2);
City city3 = new City(80, 180);
TourManager.addCity(city3);
City city4 = new City(140, 180);
TourManager.addCity(city4);
City city5 = new City(20, 160);
TourManager.addCity(city5);
City city6 = new City(100, 160);
TourManager.addCity(city6);
City city7 = new City(200, 160);
TourManager.addCity(city7);
City city8 = new City(140, 140);
TourManager.addCity(city8);
City city9 = new City(40, 120);
TourManager.addCity(city9);
City city10 = new City(100, 120);
TourManager.addCity(city10);
City city11 = new City(180, 100);
TourManager.addCity(city11);
City city12 = new City(60, 80);
TourManager.addCity(city12);
City city13 = new City(120, 80);
TourManager.addCity(city13);
City city14 = new City(180, 60);
TourManager.addCity(city14);
City city15 = new City(20, 40);
TourManager.addCity(city15);
City city16 = new City(100, 40);
TourManager.addCity(city16);
City city17 = new City(200, 40);
TourManager.addCity(city17);
City city18 = new City(20, 20);
33
TourManager.addCity(city18);
City city19 = new City(60, 20);
TourManager.addCity(city19);
City city20 = new City(160, 20);
TourManager.addCity(city20);
// Set initial temp
double temp = 10000;
// Cooling rate
double coolingRate = 0.003;
// Initialize intial solution
Tour currentSolution = new Tour();
currentSolution.generateIndividual();
System.out.println("Initial solution distance: " + currentSolution.getDistance());
// Set as current best
Tour best = new Tour(currentSolution.getTour());
// Loop until system has cooled
while (temp > 1) {
// Create new neighbour tour
Tour newSolution = new Tour(currentSolution.getTour());
// Get a random positions in the tour
int tourPos1 = (int) (newSolution.tourSize() * Math.random());
int tourPos2 = (int) (newSolution.tourSize() * Math.random());
// Get the cities at selected positions in the tour
City citySwap1 = newSolution.getCity(tourPos1);
City citySwap2 = newSolution.getCity(tourPos2);
// Swap them
newSolution.setCity(tourPos2, citySwap1);
newSolution.setCity(tourPos1, citySwap2);
// Get energy of solutions
int currentEnergy = currentSolution.getDistance();
int neighbourEnergy = newSolution.getDistance();
// Decide if we should accept the neighbour
if (acceptanceProbability(currentEnergy, neighbourEnergy, temp) > Math.random()) {
currentSolution = new Tour(newSolution.getTour());
}
if (currentSolution.getDistance() < best.getDistance()) {
best = new Tour(currentSolution.getTour());
}
temp *= 1-coolingRate;
}
System.out.println("Final solution distance: " + best.getDistance());
System.out.println("Tour: " + best);
}}
34
Output:
D:\AI Lab>javac SimulatedAnnealing.java
35
Result:
Thus, TSP was implemented successfully using Simulated Annealing and the output is
verified.
36
Ex.No. 6 Implementation of Alpha-Beta Search
Aim:
To find the optimal solution for the given game tree using Alpha-Beta search algorithm.
Algorithm:
Step5: Return step 4 until if beta <= alpha, and return bestVal
Step8: if beta <= alpha, stop the program and return bestVal
37
Program:
import java.io.*;
class AlphaBeta {
// Initial values of Alpha and Beta
static int MAX = 1000;
static int MIN = -1000;
// Returns optimal value for current player (Initially called for root and maximizer)
static int minimax(int depth, int nodeIndex,Boolean maximizingPlayer,int values[], int alpha,int
beta)
{
// Terminating condition. i.e leaf node is reached
if (depth == 3)
return values[nodeIndex];
if (maximizingPlayer)
{
int best = MIN;
// Recur for left and right children
for (int i = 0; i < 2; i++){
int val = minimax(depth + 1, nodeIndex * 2 + i,false, values, alpha, beta);
best = Math.max(best, val);
alpha = Math.max(alpha, best);
// Alpha Beta Pruning
if (beta <= alpha)
break;
}
return best;
}
else
{
int best = MAX;
// Recur for left and right children
for (int i = 0; i < 2; i++)
{
int val = minimax(depth + 1, nodeIndex * 2 + i,true, values, alpha, beta);
best = Math.min(best, val);
beta = Math.min(beta, best);
// Alpha Beta Pruning
if (beta <= alpha)
break;
}
return best;
}
}
// Driver Code
public static void main (String[] args)
{
int values[] = {3, 5, 6, 9, 1, 2, 0, -1};
System.out.println("The optimal value is : " +minimax(0, 0, true, values, MIN, MAX));
}}
38
Output:
39
Result:
Thus, Alpha beta search algorithm was implemented successfully and the output is
verified.
40
Ex.No.7 Implement Graph Coloring Problem using Backtracking Algorithm
Aim:
To solve the graph coloring problem for the following graph using backtracking search
algorithm.
Algorithm:
Step1: Confirm whether it is valid to color the current vertex with the current color (by checking
whether any of its adjacent vertices are colored with the same color).
If yes then color it and otherwise try a different color.
Check if all vertices are colored or not.
If not then move to the next adjacent uncolored vertex.
Step2: If no other color is available then backtrack (i.e. un-color last colored vertex).
Here backtracking means to stop further recursive calls on adjacent vertices by returning false.
Step3: If the same color for current vertex, then goto step 1.2 otherwise goto step 2.
Step4: Repeat step 2 and 3 until all the vertex to be colored.
41
Program:
import java.util.ArrayList;
import java.util.List;
class Vertex {
String name;
List<Vertex> adjacentVertices;
boolean colored;
String color;
public Vertex(String name) {
this.name = name;
this.adjacentVertices = new ArrayList<>();
this.colored =false;
this.color = "";
}
//connect two verticess bi-directional
public void addNeighbor(Vertex vertex){
this.adjacentVertices.add(vertex);
vertex.adjacentVertices.add(this);
}
}
class Coloring {
String colors[];
int colorCount;
int numberOfVertices;
public Coloring(String[] colors, int N) {
this.colors = colors;
this.numberOfVertices = N;
}
public boolean setColors(Vertex vertex){
//Step: 1
for(int colorIndex=0; colorIndex<colors.length; colorIndex++){
//Step-1.1: checking validity
if(!canColorWith(colorIndex, vertex))
42
continue;
//Step-1.2: continue coloring
vertex.color=colors[colorIndex];
vertex.colored=true;
colorCount++;
//Step-1.3: check whether all vertices colored?
if(colorCount== numberOfVertices) //base case
return true;
//Step-1.4: next uncolored vertex
for(Vertex nbrvertex: vertex.adjacentVertices){
if (!nbrvertex.colored){
if(setColors(nbrvertex))
return true;
}
}
}
//Step-4: backtrack
vertex.colored = false;
vertex.color = "";
return false;
}
//Function to check whether it is valid to color with color[colorIndex]
boolean canColorWith(int colorIndex, Vertex vertex) {
for(Vertex nbrvertex: vertex.adjacentVertices){
if(nbrvertex.colored && nbrvertex.color.equals(colors[colorIndex]))
return false;
}
return true;
}
}
public class CSPSolver{
public static void main(String args[]){
//define vertices
Vertex vertices[]= {new Vertex("A"), new Vertex("B"), new Vertex("C"), new Vertex("D"),new
43
Vertex("E")};
//join vertices
vertices[0].addNeighbor(vertices[1]);
vertices[1].addNeighbor(vertices[3]);
vertices[3].addNeighbor(vertices[2]);
vertices[2].addNeighbor(vertices[0]);
vertices[2].addNeighbor(vertices[4]);
vertices[4].addNeighbor(vertices[3]);
//define colors
String colors[] = {"Green","Blue","Red"};
//create coloring object
Coloring coloring = new Coloring(colors, vertices.length);
//start coloring with vertex-A
boolean hasSolution = coloring.setColors(vertices[0]);
//check if coloring was successful
if (!hasSolution)
System.out.println("No Solution");
else {
for (Vertex vertex: vertices){
System.out.println(vertex.name + " "+ vertex.color +"\n");
}}}}
44
Output:
B Blue
C Blue
D Green
E Red
45
Result:
Thus, the graph coloring problem was implemented successfully and the output is
verified successfully.
46
Ex.No.8 Implement N Queens Problem using Random Restart Hill Climbing
Algorithm
Aim:
To solve N-Queens problem with the help of Random Restart Hill Climbing algorithm.
Algorithm :
Random Restart Hill Climbing:
47
Program:
NQueen.java
HillClimbingRestart.java
import java.util.Scanner;
import java.util.Random;
public class HillClimbingRandomRestart {
private static int n ;
private static int stepsClimbedAfterLastRestart = 0;
private static int stepsClimbed =0;
private static int heuristic = 0;
private static int randomRestarts = 0;
//Method to create a new random board
48
public static NQueen[] generateBoard() {
NQueen[] startBoard = new NQueen[n];
Random rndm = new Random();
for(int i=0; i<n; i++){
startBoard[i] = new NQueen(rndm.nextInt(n), i);
}
return startBoard;
}
//Method to print the Current State
private static void printState (NQueen[] state) {
//Creating temporary board from the present board
int[][] tempBoard = new int[n][n];
for (int i=0; i<n; i++) {
//Get the positions of Queen from the Present board and set those positions as 1 in temp board
tempBoard[state[i].getRow()][state[i].getColumn()]=1;
}
System.out.println();
for (int i=0; i<n; i++) {
for (int j= 0; j < n; j++) {
System.out.print(tempBoard[i][j] + " ");
}
System.out.println();
}
}
// Method to find Heuristics of a state
public static int findHeuristic (NQueen[] state) {
int heuristic = 0;
for (int i = 0; i< state.length; i++) {
for (int j=i+1; j<state.length; j++ ) {
if (state[i].ifConflict(state[j])) {
heuristic++;
}
}
}
return heuristic;
}
// Method to get the next board with lower heuristic
public static NQueen[] nextBoard (NQueen[] presentBoard) {
NQueen[] nextBoard = new NQueen[n];
NQueen[] tmpBoard = new NQueen[n];
int presentHeuristic = findHeuristic(presentBoard);
int bestHeuristic = presentHeuristic;
int tempH;
for (int i=0; i<n; i++) {
// Copy present board as best board and temp board
nextBoard[i] = new NQueen(presentBoard[i].getRow(), presentBoard[i].getColumn());
tmpBoard[i] = nextBoard[i];
}
// Iterate each column
for (int i=0; i<n; i++) {
if (i>0)
49
tmpBoard[i-1] = new NQueen (presentBoard[i-1].getRow(), presentBoard[i-1].getColumn());
tmpBoard[i] = new NQueen (0, tmpBoard[i].getColumn());
// Iterate each row
for (int j=0; j<n; j++) {
//Get the heuristic
tempH = findHeuristic(tmpBoard);
//Check if temp board better than best board
if (tempH < bestHeuristic) {
bestHeuristic = tempH;
// Copy the temp board as best board
for (int k=0; k<n; k++) {
nextBoard[k] = new NQueen(tmpBoard[k].getRow(), tmpBoard[k].getColumn());
}
}
//Move the queen
if (tmpBoard[i].getRow()!=n-1)
tmpBoard[i].move();
}
}
//Check whether the present bord and the best board found have same heuristic
//Then randomly generate new board and assign it to best board
if (bestHeuristic == presentHeuristic) {
randomRestarts++;
stepsClimbedAfterLastRestart = 0;
nextBoard = generateBoard();
heuristic = findHeuristic(nextBoard);
} else
heuristic = bestHeuristic;
stepsClimbed++;
stepsClimbedAfterLastRestart++;
return nextBoard;
}
public static void main(String[] args) {
int presentHeuristic;
Scanner s=new Scanner(System.in);
while (true){
System.out.println("Enter the number of Queens :");
n = s.nextInt();
if ( n == 2 || n ==3) {
System.out.println("No Solution possible for "+n+" Queens. Please enter another number");
}
else
break;
}
System.out.println("Solution to "+n+" queens using hill climbing with random restart:");
//Creating the initial Board
NQueen[] presentBoard = generateBoard();
presentHeuristic = findHeuristic(presentBoard);
// test if the present board is the solution board
while (presentHeuristic != 0) {
// Get the next board
50
// printState(presentBoard);
presentBoard = nextBoard(presentBoard);
presentHeuristic = heuristic;
}
//Printing the solution
printState(presentBoard);
System.out.println("\nTotal number of Steps Climbed: " + stepsClimbed);
System.out.println("Number of random restarts: " + randomRestarts);
System.out.println("Steps Climbed after last restart: " + stepsClimbedAfterLastRestart);
}
}
51
Output:
00000100
00010000
01000000
00000001
00001000
00000010
10000000
00100000
52
Result:
Thus, the N Queen problem is implemented successfully using Hill climbing algorithm
and the output is verified.
53
54
Ex.No.9 Implement Propositional Logic
Aim:
To represent formulas of propositional logic and calculate the truth value for the given
terms.
55
Algorithm:
Step1: Create an interface Wff to get the convert the input as logical values.
Step2: Create a class as PropConstant to convert the input as string.
Step3: Create a class as Valuation to evaluate the Boolean values.
Step4: Create a class as Operator to get the logical operators for evaluation.
Step5: Create a main class as PropLogicLauncher to implement the propositional logic.
56
Program:
Wff.java
public interface Wff
{
public boolean eval(Valuation val);
public String toString();
}
PropConstant.java
public class PropConstant implements Wff {
private String propConstant;
public PropConstant(String str) {
this.propConstant = str;
}
public String toString() {
return propConstant;
}
public boolean eval(Valuation val) {
return val.get(this);
}
}
Valuation.java
import java.util.HashMap;
public class Valuation {
HashMap<PropConstant, Boolean> val = new HashMap<PropConstant, Boolean>();
public boolean get(PropConstant propConstant) {
return val.get(propConstant);
}
public Boolean put(PropConstant propConstant, boolean tv) {
return val.put(propConstant, tv);
}
}
Operator.java
57
PropLogicLauncher.java
58
Output:
59
Result:
60
Ex.No.10 Implement First Order Logic
Aim:
To represent formulas of First Order Logic (FOL) and calculate the truth value for the
given terms.
Algorithm:
61
Program:
Constant.java
SimpleSentence.java
62
{
private Unifiable[] terms;
public SimpleSentence(Constant predicateName,Unifiable... args)
{
this.terms = new Unifiable[args.length + 1];
terms[0] = predicateName;
System.arraycopy(args, 0, terms, 1,args.length);
}
private SimpleSentence(Unifiable... args)
{
terms = args
}
public String toString()
{
String s = null;
for (Unifiable p : terms)
if (s == null)
s = p.toString();
else
s += " " + p;
if (s == null)
return "null";
return "(" + s + ")";
}
public int length()
{
return terms.length;
}
public Unifiable getTerm(int index)
{
return terms[index];
}
SubstitutionSet.java
63
}
public Unifiable getBinding(Variable v)
{
return (Unifiable)bindings.get(v);
}
public boolean isBound(Variable v)
{
return bindings.get(v) != null;
}
public String toString()
{
return "Bindings:[" + bindings + "]";
}
64
Output:
65
Result:
Thus, the First Order Logic was implemented successfully and the output is verified.
66
Ex.No. 11 Implement Block World problem using Classical Planning algorithms
Aim:
To implement Block World problem using Classical Planning algorithms.
Algorithm:
Step4: Define the preconditions as On(b, x) Clear (b) Clear (y) Block (b) Block (y)
(b_=x) (b_=y) (x_=y)
Step5: Define the EFFECT as On(b, y) Clear (x) ¬On(b, x) ¬Clear (y))
67
Program:
68
neg = new ArrayList<String>();
neg.add("na");
neg.add("tc");
pos = new ArrayList<String>();
pos.add("oca");
planner.addOperator("sCA", precond, neg, pos);
precond = new ArrayList<String>();
precond.add("nb");
precond.add("td");
precond.add("nd");
neg = new ArrayList<String>();
neg.add("nb");
neg.add("td");
pos = new ArrayList<String>();
pos.add("odb");
planner.addOperator("sDB", precond, neg, pos);
List resultats = planner.findPlan();
System.out.println(resultats);
}
}
69
Output:
70
Result:
Thus, block world problem has been implemented successfully and the output is verified.
71