0% found this document useful (0 votes)
14 views33 pages

AI Lab Manual 1

The document describes multiple experiments implementing algorithms in various programming languages, including Prolog and Java. It covers the Depth First Search (DFS) for the water jug problem, Breadth First Search (BFS) for tic-tac-toe, a heuristic approach for the Traveling Salesman Problem (TSP), and a hill-climbing algorithm for solving the 8-puzzle problem. Each experiment includes code snippets and outputs demonstrating the functionality of the implemented algorithms.

Uploaded by

Srisurya
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)
14 views33 pages

AI Lab Manual 1

The document describes multiple experiments implementing algorithms in various programming languages, including Prolog and Java. It covers the Depth First Search (DFS) for the water jug problem, Breadth First Search (BFS) for tic-tac-toe, a heuristic approach for the Traveling Salesman Problem (TSP), and a hill-climbing algorithm for solving the 8-puzzle problem. Each experiment includes code snippets and outputs demonstrating the functionality of the implemented algorithms.

Uploaded by

Srisurya
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/ 33

Experiment-1:

Implementation of DFS for water jug problem using LISP/PROLOG


PROGRAM (Prolog) :

Software used: SWI-Prolog

Program Listing:
min(X,Y,X):-X<Y,!.
min(_,Y,Y).

rev(L,R):-revacc(L,[],R).
revacc([],R,R):-!.
revacc([H|T],A,R):-revacc(T,[H|A],R).

%Solve water jug problem using DFS


%X,Y are initial contents, Nx,Ny are final contents of jug1 of capacity _ and jug2 of
capacity My respectively after pouring from jug1 into jug2
chk(_,X,My,Y,Nx,Ny):- X>0,Y<My,Ey is My-Y,min(X,Ey,P),
Nx is X-P,Ny is Y+P.
%Given 3 jugs of capacities Mx,My,Mz and filled with X,Y,Z units of a liquid
respectively,give steps so that finally they contain Fx,Fy,Fz units of the liquid
respectively.
jug(Mx,My,Mz,X,Y,Z,Fx,Fy,Fz):-jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,[],['Initially']).

jug(_,Fx,_,Fy,_,Fz,Fx,Fy,Fz,T,R):-
!,rev([[Fx,Fy,Fz],[Fx,Fy,Fz]|T],TR),rev(['Finally'|R],RR),display(TR,RR).
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-chk(Mx,X,My,Y,Nx,Ny),not(member([Nx,Ny,Z],T))
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-chk(Mx,X,Mz,Z,Nx,Nz),not(member([Nx,Y,Nz],T))
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-chk(My,Y,Mz,Z,Ny,Nz),not(member([X,Ny,Nz],T))
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-chk(My,Y,Mx,X,Ny,Nx),not(member([Nx,Ny,Z],T))
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-chk(Mz,Z,Mx,X,Nz,Nx),not(member([Nx,Y,Nz],T))
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-chk(Mz,Z,My,Y,Nz,Ny),not(member([X,Ny,Nz],T))

display([],[]):-!.
display([T1|T],[R1|R]):-write(R1),write(' : '),write(T1),nl,display(T,R).

Output:

8 ?- jug(8,5,3,8,0,0,4,4,0).
Initially : [8, 0, 0]
Pour liquid from jug1 into jug2 : [3, 5, 0]
Pour liquid from jug1 into jug3 : [0, 5, 3]
Pour liquid from jug2 into jug1 : [5, 0, 3]
Pour liquid from jug3 into jug2 : [5, 3, 0]
Pour liquid from jug1 into jug3 : [2, 3, 3]
Pour liquid from jug3 into jug2 : [2, 5, 1]
Pour liquid from jug2 into jug1 : [7, 0, 1]
Pour liquid from jug3 into jug2 : [7, 1, 0]
Pour liquid from jug1 into jug3 : [4, 1, 3]
Pour liquid from jug3 into jug2 : [4, 4, 0]
Finally : [4, 4, 0]

Yes
9 ?-
Experiment-2:
Implementation of BFS for tic-tac-toe problem using LISP/PROLOG/Java
PROGRAM (Java):

import java.util.Scanner;

class Main {

public static void main(String[] args) {

//Create a 3x3 array that represents our tic tac toe board

char[][] board = new char[3][3];

//Initialize our board with dashes (empty positions)

for(int i = 0; i< 3; i++) {

for(int j = 0; j < 3; j++) {

board[i][j] = '-';

//Create a Scanner and ask the players for their names

Scanner in = new Scanner(System.in);

System.out.println("Let's play Tic Tac Toe!");

System.out.print("Player 1, what is your name? ");

String p1 = in.nextLine();

System.out.print("Player 2, what is your name? ");

String p2 = in.nextLine();

//Create a player1 boolean that is true if it is player 1's turn and false if it is player 2's turn

boolean player1 = true;

//Create a gameEndedboolean and use it as the condition in the while loop

booleangameEnded = false;

while(!gameEnded) {

//Draw the board

drawBoard(board);
//Print whose turn it is

if(player1) {

System.out.println(p1 + "'s Turn (x):");

} else {

System.out.println(p2 + "'s Turn (o):");

//Create a char variable that stores either 'x' or 'o' based on what player's turn it is

char c = '-';

if(player1) {

c = 'x';

} else {

c = 'o';

//Create row and col variables which represent indexes that correspond to a position on our board

int row = 0;

int col = 0;

//Only break out of the while loop once the user enters a valid position

while(true) {

//Ask the user for what position they want to place their x or o

System.out.print("Enter a row number (0, 1, or 2): ");

row = in.nextInt();

System.out.print("Enter a column number (0, 1, or 2): ");

col = in.nextInt();

//Check if the row and col are 0, 1, or 2

if(rw < 0 || col < 0 || row > 2 || col > 2) {

System.out.println("This position is off the bounds of the board! Try again.");

//Check if the position on the board the user entered is empty (has a -) or not

} else if(board[row][col] != '-') {


System.out.println("Someone has already made a move at this position! Try
again.");

//Otherwise, the position is valid so break out of the while loop

} else {

break;

//Set the position on the board at row, col to c

board[row][col] = c;

//Check to see if either player has won

if(playerHasWon(board) == 'x') {

System.out.println(p1 + " has won!");

gameEnded = true;

} else if(playerHasWon(board) == 'o') {

System.out.println(p2 + " has won!");

gameEnded = true;

} else {

//If neither player has won, check to see if there has been a tie (if the board is full)

if(boardIsFull(board)) {

System.out.println("It's a tie!");

gameEnded = true;

} else {

//If player1 is true, make it false, and vice versa; this way, the players alternate each turn

player1 = !player1

}
}

//Draw the board at the end of the game

drawBoard(board);

//Make a function to draw the tic tac toe board

public static void drawBoard(char[][] board) {

System.out.println("Board:");

for(int i = 0; i< 3; i++) {

//The inner for loop prints out each row of the board

for(int j = 0; j < 3; j++) {

System.out.print(board[i][j]);

//This print statement makes a new line so that each row is on a separate line

System.out.println();

//Make a function to see if someone has won and return the winning char

public static char playerHasWon(char[][] board) {

//Check each row

for(int i = 0; i< 3; i++) {

if(board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != '-') {

return board[i][0];

//Check each column


for(int j = 0; j < 3; j++) {

if(board[0][j] == board[1][j] && board[1][j] == board[2][j] && board[0][j] != '-') {

return board[0][j];

//Check the diagonals

if(board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '-') {

return board[0][0];

if(board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[2][0] != '-') {

return board[2][0];

//Otherwise nobody has not won yet

return ' ';

//Make a function to check if all of the positions on the board have been filled

public static booleanboardIsFull(char[][] board) {

for(int i = 0; i< 3; i++) {

for(int j = 0; j < 3; j++) {

if(board[i][j] == '-') {

return false;

return true;

}
}

Output:
Experiment-3:
Implementation of TSP using heuristic approach using Java/LISP/Prolog
PROGRAM (Java):

// Java implementation of the approach


classGFG
{

// Function to find the minimum weight


// Hamiltonian Cycle
staticinttsp(int[][] graph, boolean[] v,
intcurrPos, intn,
intcount, intcost, intans)
{

// If last node is reached and it has a link


// to the starting node i.e the source then
// keep the minimum value out of the total cost
// of traversal and "ans"
// Finally return to check for more possible values
if(count == n && graph[currPos][0] > 0)
{
ans = Math.min(ans, cost + graph[currPos][0]);
returnans;
}

// BACKTRACKING STEP
// Loop to traverse the adjacency list
// of currPos node and increasing the count
// by 1 and cost by graph[currPos,i] value
for(inti = 0; i< n; i++)
{
if(v[i] == false&& graph[currPos][i] > 0)
{

// Mark as visited
v[i] = true;
ans = tsp(graph, v, i, n, count + 1,
cost + graph[currPos][i], ans);

// Mark ith node as unvisited


v[i] = false;
}
}
returnans;
}

// Driver code
publicstaticvoidmain(String[] args)
{

// n is the number of nodes i.e. V


intn = 4;

int[][] graph = {{0, 10, 15, 20},


{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}};
// Boolean array to check if a node
// has been visited or not
boolean[] v = newboolean[n];

// Mark 0th node as visited


v[0] = true;
intans = Integer.MAX_VALUE;

// Find the minimum weight Hamiltonian Cycle


ans = tsp(graph, v, 0, n, 1, 0, ans);

// ans is the minimum weight Hamiltonian Cycle


System.out.println(ans);
}
}

Outputs:

80
Experiment-4:
Implementation of Hill-climbing to solve 8- Puzzle Problem

PROGRAM (Java) :

EightPuzzle.java

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.Vector;

public class EightPuzzle {

/**

* @param args the command line arguments

*/

private int gn=0; // Initialize gnie. no. of moves to 0

private Board start;

private Board goal;

public void initStart() //Accept and display start board


{

System.out.println("\n\n Enter start Board : ");

start=new Board();

start.initBoard();

System.out.println("\n\nThe given start board is : ");

start.display();

public void initGoal() //Accept and display goal board

System.out.println("\n\n Enter goal Board : ");

goal=new Board();

goal.initBoard();

System.out.println("\n\nThe given goal board is : ");

goal.display();

public void solve() // Solve puzzle using A* algorithm

Board cur = start;

while(true)

System.out.println("\n\nBoard after "+gn+" moves : ");

cur.display();

if(cur.equals(goal)) //Check if goal is achieved nad return

System.out.println("\nGoal state achieved.");

return;
}

gn++; // Increment gn as per moves

cur = cur.nextMove(gn, goal); // get the board after next move

public static void main(String[] args) {

// TODO code application logic here

EightPuzzle ep = new EightPuzzle(); // Instantiate and solve the puzzle

ep.initStart();

ep.initGoal();

System.out.println("\n\nThe board is solved as : \n");

ep.solve();

Board.java

import java.util.Scanner;

import javax.swing.JOptionPane;
//board class for eight puzzle matrix

public class Board {

private String board[][];

private int blankX,blankY; // co-ordinates for blank tile

public Board()

this.board = new String[3][3];

public Board(Board b) //constructor to initialise Board

this.board = b.board;

this.blankX = b.blankX;

this.blankY = b.blankY;

public void initBoard() //initialize the board

Scanner inp = new Scanner(System.in);

System.out.println("\nEnter one tile as '-' ie. Blank tile\n");

for(int i=0; i<3; i++)

for(int j=0; j<3; j++)

board[i][j] = JOptionPane.showInputDialog("Enter the value of tile ["+i+"]["+(j)+"] : ");


if(board[i][j].equals("-")) //store the location of blank symbol

blankX=i;

blankY=j;

public String[][] getBoard()

return board;

public void setBoard(String[][] board) // Set the board puzzle matrix

for(int i=0; i<3; i++)

for(int j=0; j<3; j++)

this.board[i][j] = board[i][j];

public int getBlankX()

{
return blankX;

public int getBlankY()

return blankY;

public void setBlankX(int x)

blankX = x;

public void setBlankY(int y)

blankY = y;

public void display()

for(int i=0; i<3; i++)

for(int j=0; j<3; j++)

System.out.print("\t"+board[i][j]);

System.out.println();

}
public Board nextMove(int gn, Board goal) //method to check possible moves and select
optimum

Board temp = new Board();

Board next = new Board();

int minFn = 999;

System.out.println("\nPossible moves are : ");

if(blankY>0) // Condition for possible left move

temp.setBoard(board);

temp.swap(blankX, blankY, blankX, blankY-1); // Swap blank tile

int fn = (temp.getHn(goal)+gn); // Calculate fn = hn + gn

System.out.println("\nForFn = "+fn+" : ");

temp.display();

if(fn<minFn) // Check for minimum fn and set the next board accordingly

minFn = fn;

next.setBoard(temp.board);

next.setBlankX(blankX);

next.setBlankY(blankY-1);

if(blankY<2) // Condition for possible right move

temp.setBoard(board);

temp.swap(blankX, blankY, blankX, blankY+1);

int fn = (temp.getHn(goal)+gn);
System.out.println("\nForFn = "+fn+" : ");

temp.display();

if(fn<minFn)

minFn = fn;

next.setBoard(temp.board);

next.setBlankX(blankX);

next.setBlankY(blankY+1);

if(blankX>0) // Condition for possible up move

temp.setBoard(board);

temp.swap(blankX, blankY, blankX-1, blankY);

int fn = (temp.getHn(goal)+gn);

System.out.println("\nForFn = "+fn+" : ");

temp.display();

if(fn<minFn)

minFn = fn;

next.setBoard(temp.board);

next.setBlankX(blankX-1);

next.setBlankY(blankY);

if(blankX<2) // Condition for possible down move

{
temp.setBoard(board);

temp.swap(blankX, blankY, blankX+1, blankY);

int fn = (temp.getHn(goal)+gn);

System.out.println("\nForFn = "+fn+" : ");

temp.display();

if(fn<minFn)

minFn = fn;

next.setBoard(temp.board);

next.setBlankX(blankX+1);

next.setBlankY(blankY);

return next; // return board with min fn

public void swap(int i1, int j1, int i2, int j2) // Swap tile values

String temp = board[i1][j1];

board[i1][j1] = board[i2][j2];

board[i2][j2] = temp;

public boolean equals(Board b) // check for board equality

for(int i=0; i<3; i++)


{

for(int j=0; j<3; j++)

if(!this.board[i][j].equals(b.board[i][j]))

return false;

return true;

public int getHn(Board goal) // get hn by Hamming method

int hn = 0;

for(int i=0; i<3; i++)

for(int j=0; j<3; j++)

if(!this.board[i][j].equals(goal.board[i][j]))

hn++;

return hn;
}

/*

Enter start Board :

Enter one tile as '-' ie. Blank tile

The given start board is :

- a c

h b d

g f e

Enter goal Board :

Enter one tile as '-' ie. Blank tile

The given goal board is :

a b c

h - d

g f e
The board is solved as :

Board after 0 moves :

- a c

h b d

g f e

Possible moves are :

For Fn = 3 :

a - c

h b d

g f e

For Fn = 5 :

h a c

- b d

g f e

Board after 1 moves :

a - c

h b d

g f e

Possible moves are :


For Fn = 5 :

- a c

h b d

g f e

For Fn = 5 :

a c -

h b d

g f e

For Fn = 2 :

a b c

h - d

g f e

Board after 2 moves :

a b c

h - d

g f e

Goal state achieved.

*/
Experiment-5:
Implementation of Monkey Banana Problem using LISP/PROLOG

PROGRAM (Prolog) :

move(state(middle,onbox,middle,hasnot),
grasp,
state(middle,onbox,middle,has)).
move(state(P,onfloor,P,H),
climb,
state(P,onbox,P,H)).
move(state(P1,onfloor,P1,H),
drag(P1,P2),
state(P2,onfloor,P2,H)).
move(state(P1,onfloor,B,H),
walk(P1,P2),
state(P2,onfloor,B,H)).
canget(state(_,_,_,has)).
canget(State1):-
move(State1,_,State2),
canget(State2).

Output:

| ?- [monkey_banana].
compiling D:/TP Prolog/Sample_Codes/monkey_banana.pl for byte code...
D:/TP Prolog/Sample_Codes/monkey_banana.pl compiled, 17 lines read - 2167 bytes
written, 19 ms

(31 ms) yes


| ?- canget(state(atdoor, onfloor, atwindow, hasnot)).

true ?

yes
| ?- trace
.
The debugger will first creep -- showing everything (trace)

yes
{trace}
| ?- canget(state(atdoor, onfloor, atwindow, hasnot)).
1 1 Call: canget(state(atdoor,onfloor,atwindow,hasnot)) ?
2 2 Call: move(state(atdoor,onfloor,atwindow,hasnot),_52,_92) ?
2 2
Exit:move(state(atdoor,onfloor,atwindow,hasnot),walk(atdoor,_80),state(_80,onfl
oor,atwindow,hasnot)) ?
3 2 Call: canget(state(_80,onfloor,atwindow,hasnot)) ?
4 3 Call: move(state(_80,onfloor,atwindow,hasnot),_110,_150) ?
4 3 Exit:
move(state(atwindow,onfloor,atwindow,hasnot),climb,state(atwindow,onbox,atwindo
w,hasnot)) ?
5 3 Call: canget(state(atwindow,onbox,atwindow,hasnot)) ?
6 4 Call: move(state(atwindow,onbox,atwindow,hasnot),_165,_205) ?
6 4 Fail: move(state(atwindow,onbox,atwindow,hasnot),_165,_193) ?
5 3 Fail: canget(state(atwindow,onbox,atwindow,hasnot)) ?
4 3 Redo:
move(state(atwindow,onfloor,atwindow,hasnot),climb,state(atwindow,onbox,atwindo
w,hasnot)) ?
4 3 Exit:
move(state(atwindow,onfloor,atwindow,hasnot),drag(atwindow,_138),state(_138,onf
loor,_138,hasnot)) ?
5 3 Call: canget(state(_138,onfloor,_138,hasnot)) ?
6 4 Call: move(state(_138,onfloor,_138,hasnot),_168,_208) ?
6 4 Exit:
move(state(_138,onfloor,_138,hasnot),climb,state(_138,onbox,_138,hasnot)) ?
7 4 Call: canget(state(_138,onbox,_138,hasnot)) ?
8 5 Call: move(state(_138,onbox,_138,hasnot),_223,_263) ?
8 5 Exit:
move(state(middle,onbox,middle,hasnot),grasp,state(middle,onbox,middle,has)) ?
9 5 Call: canget(state(middle,onbox,middle,has)) ?
9 5 Exit: canget(state(middle,onbox,middle,has)) ?
7 4 Exit: canget(state(middle,onbox,middle,hasnot)) ?
5 3 Exit: canget(state(middle,onfloor,middle,hasnot)) ?
3 2 Exit: canget(state(atwindow,onfloor,atwindow,hasnot)) ?
1 1 Exit: canget(state(atdoor,onfloor,atwindow,hasnot)) ?

true ?

(78 ms) yes


Experiment-6:
Implementation of A* Algorithm using LISP/PROLOG
PROGRAM (Prolog) :

/* 8_puzzle.pl */

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% A* Algorithm
%%%
%%%
%%% Nodes have form S#D#F#A
%%% where S describes the state or configuration
%%% D is the depth of the node
%%% F is the evaluation function value
%%% A is the ancestor list for the node

:- op(400,yfx,'#'). /* Node builder notation */

solve(State,Soln) :- f_function(State,0,F),
search([State#0#F#[]],S), reverse(S,Soln).

f_function(State,D,F) :- h_function(State,H),
F is D + H.

search([State#_#_#Soln|_], Soln) :- goal(State).


search([B|R],S) :- expand(B,Children),
insert_all(Children,R,Open),
search(Open,S).

insert_all([F|R],Open1,Open3) :- insert(F,Open1,Open2),
insert_all(R,Open2,Open3).
insert_all([],Open,Open).

insert(B,Open,Open) :- repeat_node(B,Open), ! .
insert(B,[C|R],[B,C|R]) :- cheaper(B,C), ! .
insert(B,[B1|R],[B1|S]) :- insert(B,R,S), !.
insert(B,[],[B]).

repeat_node(P#_#_#_, [P#_#_#_|_]).

cheaper( _#_#F1#_ , _#_#F2#_ ) :- F1 < F2.

expand(State#D#_#S,All_My_Children) :-
bagof(Child#D1#F#[Move|S],
(D1 is D+1,
move(State,Child,Move),
f_function(Child,D1,F)),
All_My_Children).
Experiment-9:
Implementation of Hill Climbing Algorithm using LISP/PROLOG

Prolog program for solving the blocks problem using hill climbing

PROGRAM (Prolog) :

/******************************************************************************Write a prolog
program for solving the blocks problem using hill climbing
*******************************************************************************/
%trace
domains
heuristic_val = integer
top_type = top(integer)
node_type = on(integer,integer)

nodetype_list = node_type*
top_list = top_type*
file = xoutput
database
curr_db_list(nodetype_list,top_list,heuristic_val)
child_db_list(nodetype_list,top_list,heuristic_val)
best_child(nodetype_list,top_list,heuristic_val)

db_on(integer,integer)
db_top(integer)

heuristic_value_db(integer)
temp_nodelist(nodetype_list)
temp_toplist(top_list)

predicates
block(integer)
initial_state
retract_all_db
write_list
writelist(nodetype_list)

get_heuristic_value(integer)
compute_heuristic

create_node_top_list(nodetype_list,top_list)
create_node_list
create_top_list
append_node(nodetype_list,nodetype_list,nodetype_list)
append_top(top_list,top_list,top_list)

find_children(nodetype_list,top_list,integer)
find_path
find_best_child
move_block(integer,nodetype_list,top_list)

copy_on_top_to_db(nodetype_list,top_list)
copy_on_to_db(nodetype_list)
copy_top_to_db(top_list)

delete_curr_best_db
clauses

write_list:-
curr_db_list(NodeList,TopList,HVal),
writelist(NodeList),
nl,
nl,
fail.

writelist([]):- nl.
writelist([Head|Tail]):-
write(Head),
writelist(Tail).

retract_all_db:-
retractall(curr_db_list(_,_,_)),
retractall(db_on(_,_)),
retractall(db_top(_)),
retractall(heuristic_value_db(_)),
retractall(temp_nodelist(_)),
retractall(temp_toplist(_)),
retractall(child_db_list(_,_,_)),
retractall(best_child(_,_,_)).

block(1).
block(2).
block(3).
block(4).
block(5).
block(6).
block(7).
block(8).
block(0).

initial_state:-
assert(db_on(1,8)),
assert(db_on(8,7)),
assert(db_on(7,6)),
assert(db_on(6,5)),
assert(db_on(5,4)),
assert(db_on(4,3)),
assert(db_on(3,2)),
assert(db_on(2,0)),
assert(db_top(1)),
create_node_top_list(NodeList,TopList),
get_heuristic_value(HeuristicVal),
assert(curr_db_list(NodeList,TopList,HeuristicVal)),
writelist(NodeList).

delete_curr_best_db:-
retractall(best_child(_,_,_)),
assert(best_child([],[],-9999)),
retract(curr_db_list(_,_,_)),
!.

find_path:-
curr_db_list(NodeList,TopList,HeuristicVal),
% retract(curr_db_list(NodeList,TopList,HeuristicVal)),
delete_curr_best_db,
find_children(NodeList,TopList,HeuristicVal),
find_best_child,
best_child(BestNodeList,BestTopList,BestHVal),
writelist(BestNodeList),
BestHVal<> 8,
assert(curr_db_list(BestNodeList,BestTopList,BestHVal)),
% write("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"),
find_path.

find_path:-!.

find_children(NodeList,TopList,HeuristicVal):-
retractall(db_top(_)),
retractall(db_on(_,_)),
retractall(child_db_list(_,_,_)),
copy_on_top_to_db(NodeList,TopList),
db_top(X),
move_block(X,NodeList,TopList),
fail.

find_children(NodeList,TopList,HeuristicVal):-!.

find_best_child:-
child_db_list(NodeList,TopList,HeuristicValue),
% write("-----CHILD-----------\n"),
% writelist(NodeList),
best_child(A,B,BestValue),
HeuristicValue>= BestValue,
not(best_child(NodeList,TopList,HeuristicValue)),
retract(best_child(A,B,BestValue)),
assert(best_child(NodeList,TopList,HeuristicValue)),
fail.

find_best_child:-!.

get_heuristic_value(X):-
assert(heuristic_value_db(0)),
compute_heuristic(),
heuristic_value_db(X),
retract(heuristic_value_db(X)).
% write(X,"\n").

compute_heuristic:-
block(Y),
db_on(Y,Z),
Y = Z + 1,
heuristic_value_db(OLD_VAL),
retract(heuristic_value_db(OLD_VAL)),
NEW_VAL = OLD_VAL + 1,
assert(heuristic_value_db(NEW_VAL)),
fail.

compute_heuristic:-
block(Y),
db_on(Y,Z),
Y > Z + 1,
heuristic_value_db(OLD_VAL),
retract(heuristic_value_db(OLD_VAL)),
NEW_VAL = OLD_VAL - 1,
assert(heuristic_value_db(NEW_VAL)),
fail.

compute_heuristic:-
block(Y),
db_on(Y,Z),
Y < Z,
heuristic_value_db(OLD_VAL),
retract(heuristic_value_db(OLD_VAL)),
NEW_VAL = OLD_VAL - 1,
assert(heuristic_value_db(NEW_VAL)),
fail.

compute_heuristic.

move_block(X,OldNodeList,OldTopList):-
block(Y),
X <> Y,
Y <> 0,
retractall(db_on(_,_)),
retractall(db_top(_)),
copy_on_top_to_db(OldNodeList,OldTopList),
db_top(Y),
db_on(X,Z),
Z <> 0,
retract(db_on(X,Z)),
retract(db_top(Y)),
assert(db_on(X,Y)),
assert(db_top(Z)),
get_heuristic_value(HeuristicValue),
create_node_top_list(NodeList,TopList),
not(child_db_list(NodeList,TopList,HeuristicValue)),
assert(child_db_list(NodeList,TopList,HeuristicValue)),
% write("MOVED--------------\n"),
% writelist(NodeList),
fail.

move_block(X,OldNodeList,OldTopList):-
block(Y),
X <> Y,
Y <> 0,
retractall(db_on(_,_)),
retractall(db_top(_)),
copy_on_top_to_db(OldNodeList,OldTopList),
db_top(Y),
db_on(X,Z),
Z = 0,
retract(db_on(X,Z)),
retract(db_top(Y)),
assert(db_on(X,Y)),
get_heuristic_value(HeuristicValue),
create_node_top_list(NodeList,TopList),
not(child_db_list(NodeList,TopList,HeuristicValue)),
assert(child_db_list(NodeList,TopList,HeuristicValue)),
% write("MOVED--------------\n"),
% writelist(NodeList),
fail.

move_block(X,OldNodeList,OldTopList):-
% write("\nEntering YYYY"),
block(Y),
X <> Y,
Y = 0,
retractall(db_on(_,_)),
retractall(db_top(_)),
copy_on_top_to_db(OldNodeList,OldTopList),
not(db_on(X,Y)),
db_on(X,Z),
Z <> 0,
retract(db_on(X,Z)),
assert(db_on(X,Y)),
assert(db_top(Z)),
get_heuristic_value(HeuristicValue),
create_node_top_list(NodeList,TopList),
not(child_db_list(NodeList,TopList,HeuristicValue)),
assert(child_db_list(NodeList,TopList,HeuristicValue)),
% write("MOVED--------------\n"),
% writelist(NodeList),
fail.

move_block(X,OldNodeList,OldTopList).

create_node_top_list(NodeList,TopList):-
retractall(temp_nodelist(_)),
retractall(temp_toplist(_)),
assert(temp_nodelist([])),
assert(temp_toplist([])),
create_node_list,
create_top_list,
temp_nodelist(NodeList),
temp_toplist(TopList),
retractall(temp_nodelist(_)),
retractall(temp_toplist(_)).

create_top_list:-
db_top(X),
temp_toplist(TopList),
retract(temp_toplist(TopList)),
append_top([top(X)],TopList,TopList1),
assert(temp_toplist(TopList1)),
fail.

create_top_list.

create_node_list:-
db_on(X,Y),
temp_nodelist(NodeList),
retract(temp_nodelist(NodeList)),
append_node([on(X,Y)],NodeList,NodeList1),
assert(temp_nodelist(NodeList1)),
fail.

create_node_list.

append_node([],ListB,ListB).

append_node([X|List1],List2,[X|List3]):-
append_node(List1,List2,List3).

append_top([],ListB,ListB).

append_top([X|List1],List2,[X|List3]):-
append_top(List1,List2,List3).

copy_on_top_to_db(NodeList,TopList):-
retractall(db_on(_,_)),
retractall(db_top(_)),
copy_on_to_db(NodeList),
copy_top_to_db(TopList),
!.

copy_on_to_db([]).
copy_on_to_db([on(X,Y)|Tail]):-
assert(db_on(X,Y)),
copy_on_to_db(Tail).

copy_top_to_db([]).
copy_top_to_db([top(X)|Tail]):-
assert(db_top(X)),
copy_top_to_db(Tail).
goal
clearwindow,
retract_all_db,
openwrite(xoutput,"hill.dat"),
writedevice(xoutput),
initial_state,
find_path,
closefile(xoutput),
writedevice(screen).
Output:-

on(2,0)on(3,2)on(4,3)on(5,4)on(6,5)on(7,6)on(8,7)on(1,8)
on(1,0)on(8,7)on(7,6)on(6,5)on(5,4)on(4,3)on(3,2)on(2,0)
on(8,0)on(2,0)on(3,2)on(4,3)on(5,4)on(6,5)on(7,6)on(1,0)
on(7,0)on(1,0)on(6,5)on(5,4)on(4,3)on(3,2)on(2,0)on(8,0)
on(6,0)on(8,0)on(2,0)on(3,2)on(4,3)on(5,4)on(1,0)on(7,0)
on(5,0)on(7,0)on(1,0)on(4,3)on(3,2)on(2,0)on(8,0)on(6,0)
on(4,0)on(6,0)on(8,0)on(2,0)on(3,2)on(1,0)on(7,0)on(5,0)
on(3,0)on(5,0)on(7,0)on(1,0)on(2,0)on(8,0)on(6,0)on(4,0)
on(2,1)on(4,0)on(6,0)on(8,0)on(1,0)on(7,0)on(5,0)on(3,0)
on(3,2)on(5,0)on(7,0)on(1,0)on(8,0)on(6,0)on(4,0)on(2,1)
on(4,3)on(2,1)on(6,0)on(8,0)on(1,0)on(7,0)on(5,0)on(3,2)
on(5,4)on(3,2)on(7,0)on(1,0)on(8,0)on(6,0)on(2,1)on(4,3)
on(6,5)on(4,3)on(2,1)on(8,0)on(1,0)on(7,0)on(3,2)on(5,4)
on(7,6)on(5,4)on(3,2)on(1,0)on(8,0)on(2,1)on(4,3)on(6,5)
on(8,7)on(6,5)on(4,3)on(2,1)on(1,0)on(3,2)on(5,4)on(7,6)

You might also like