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

Ai Programs

The document discusses heuristic approaches for solving the traveling salesman problem (TSP). It describes the TSP problem and constraints. For an asymmetric TSP, where costs between locations may differ based on direction, a heuristic approach is proposed that initially removes the constraint requiring a single connected tour, solving for multiple subtours instead and then modifying the solution to meet all constraints. For a symmetric TSP, where costs are the same regardless of direction, clustering locations and solving clusters individually before combining solutions is suggested. Example code for implementing these approaches in Java, Lisp or Prolog is provided.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Ai Programs

The document discusses heuristic approaches for solving the traveling salesman problem (TSP). It describes the TSP problem and constraints. For an asymmetric TSP, where costs between locations may differ based on direction, a heuristic approach is proposed that initially removes the constraint requiring a single connected tour, solving for multiple subtours instead and then modifying the solution to meet all constraints. For a symmetric TSP, where costs are the same regardless of direction, clustering locations and solving clusters individually before combining solutions is suggested. Example code for implementing these approaches in Java, Lisp or Prolog is provided.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

AI PROGRAMS

1. WATER JUG PROGRAM.

OBJECTIVE:
Write a program to solve water jug problem using
LISP/PROLOG.
THEORY:
You are on the side of the river. You are given a m liter jug
and a n liter jug where 0 < m < n. Both the jugs are initially
empty. The jugs don’t have markings to allow measuring
smaller quantities. You have to use the jugs to measure d
liters of water where d < n. Determine the minimum no of
operations to be performed to obtain d liters of water in one
of jug.
The operations you can perform are:
1. Empty a Jug
2. Fill a Jug
3. Pour water from one jug to the other until one of the jugs is
either empty or full.
Solution 1 (Always pour from m liter jug into n liter jug)
1. Fill the m litre jug and empty it into n liter jug.
2. Whenever the m liter jug becomes empty fill it.
3. Whenever the n liter jug becomes full empty it.
4. Repeat steps 1,2,3 till either n liter jug or the m liter jug
contains d litres of water.
Each of steps 1, 2 and 3 are counted as one operation that
we perform. Let us say algorithm 1 achieves the task in C1
no of operations.
Solution 2 (Always pour from n liter jug into m liter jug)
1. Fill the n liter jug and empty it into m liter jug.
2. Whenever the n liter jug becomes empty fill it.
3. Whenever the m liter jug becomes full empty it.
4. Repeat steps 1, 2 and 3 till either n liter jug or the m liter
jug contains d liters of water.
Let us say solution 2 achieves the task in C2 no of
operations. Now our final solution will be a minimum of C1
and C2. Now we illustrate how both of the solutions work.
Suppose there are a 3 liter jug and a 5 liter jug to measure 4
liters water so m = 3,n = 5 and d =
4. The associated Diophantine equation will be 3m + 5n = 4.
We use pair (x, y) to represent amounts of water inside the
3-liter jug and 5-liter jug respectively in each pouring step.
Using Solution 1, successive pouring steps are: (0,0)-
>(3,0)->(0,3)->(3,3)->(1,5)->(1,0)->(0,1)->(3,1)->(0,4) Hence
the no of operations you need to perform are 8.
Using Solution 2, successive pouring steps are: (0,0)-
>(0,5)->(3,2)->(0,2)->(2,0)->(2,5)->(3,4)
Hence the no of operations you need to perform are 6.
Therefore, we would use solution 2 to measure 4 liters of
water in 6 operations or moves.
PROGRAM:

water_jug(X,Y):-X>4,Y<3,write('4L water jug overflowed.'),n1.


water_jug(X,Y):-X<4,Y>3,write('3L water jug overflowed.'),nl.
water_jug(X,Y):-X>4,Y>3,write('Both water jugs overflowed.'),nl.

(water_jug(X,Y):-(X=:=0,Y=:=0,nl,write('4L:0 & 3L:3 (Action: Fill 3L


jug.)'),YY is 3,water_jug(X,YY));
(X=:=0,Y=:=0,nl,write('4L:4 & 3L:0 (Action: Fill 4L
jug.)'),XX is 4,water_jug(XX,Y));
(X=:=2,Y=:=0,nl,write('4L:2 & 3L:0 (Action: Goal
State Reached....)'));
(X=:=4,Y=:=0,nl,write('4L:1 & 3L:3 (Action: Pour
water from 4L to 3L jug.)'),XX is X-3,YY is 3,water_jug(XX,YY));
(X=:=0,Y=:=3,nl,write('4L:3 & 3L:0 (Action: Pour
water from 3L jug to 4L jug.)'),XX is 3,YY is 0,water_jug(XX,YY));
(X=:=1,Y=:=3,nl,write('4L:1 & 3L:0 (Action: Empty 3L
jug.)'),YY is 0,water_jug(X,YY));
(X=:=3,Y=:=0,nl,write('4L:3 & 3L:3 (Action: Fill 3L
jug.)'),YY is 3,water_jug(X,YY));
(X=:=3,Y=:=3,nl,write('4L:4 & 3L:2 (Action: Pour
water from 3L jug to 4L jug until 4L jug is full.)'),XX is X+1,YY is
Y- 1,water_jug(XX,YY));
(X=:=1,Y=:=0,nl,write('4L:0 & 3L:1 (Action: Pour
water from 4L to 3L jug.)'),XX is Y,YY is X,water_jug(XX,YY));
(X=:=0,Y=:=1,nl,write('4L:4 & 3L:1 (Action: Fill 4L
jug.)'),XX is 4,water_jug(XX,Y));
(X=:=4,Y=:=1,nl,write('4L:2 & 3L:3 (Action: Pour
water from 4L jug to 3L jug until 3L jug is full.)'),XX is X-2,YY is
Y+2,water_jug(XX,YY));
(X=:=2,Y=:=3,nl,write('4L:2 & 3L:0 (Action: Empty 3L
jug.)'),YY is 0,water_jug(X,YY));
(X=:=4,Y=:=2,nl,write('4L:0 & 3L:2 (Action: Empty 4L
jug.)'),XX is 0,water_jug(XX,Y));
(X=:=0,Y=:=2,nl,write('4L:2 & 3L:0 (Action: Pour
water from 3L jug to 4L jug.)'),XX is Y,YY is X,water_jug(XX,YY))).

OUTCOME:
2.TIC-TAC-TOE PROGRAM:

OBJECTIVE:
Implementation of BFS for tic-tac-toe problem using
PROLOG.

THEORY:

Rules of the Game


The game is to be played between two people (in this
program between HUMAN and COMPUTER).
One of the player chooses ‘O’ and the other ‘X’ to
mark their respective cells.
The game starts with one of the players and the
game ends when one of the players has one whole row/
column/ diagonal filled with his/her respective
character (‘O’ or ‘X’).
If no one wins, then the game is said to be draw.

O X O
O X X
X O X

Implementation
In our program the moves taken by the computer and the
human are chosen randomly. We use rand() function for
this.

PROGRAM:
ordered_line(1, 2, 3). ordered_line(4, 5, 6). ordered_line(7, 8, 9).
ordered_line(1, 4, 7). ordered_line(2, 5, 8). ordered_line(3, 6,
9).
ordered_line(1, 5, 9). ordered_line(3, 5, 7).

line(A, B, C) :- ordered_line(A, B, C). line(A, B, C) :-


ordered_line(A, C, B).
line(A, B, C) :- ordered_line(B, A, C). line(A, B, C) :-
ordered_line(B, C, A).
line(A, B, C) :- ordered_line(C, A, B). line(A, B, C) :-
ordered_line(C, B, A).

full(A) :- x(A). full(A) :- o(A). empty(A) :- \+(full(A)).


same(A, A). different(A, B) :- \+(same(A, B)).

move(C) :- rule1(C).
move(A) :- good(A), empty(A), !. good(1). good(3). good(7).
good(9). good(5). good(2). good(4). good(6). good(8).
all_full :- full(1), full(2), full(3), full(4), full(5),
full(6), full(7), full(8), full(9).

% this rule is to block if there is going to be two consecutive


moves, then it should prevent the third move
rule1(C) :- line(A,B,C), o(A), o(B), empty(C), !.
rule1(C) :- line(A,B,C), x(A), x(B), empty(C), !.
rule1(5) :- empty(5).
rule1(C) :- o(A), A \= 2, A \= 4, A \= 6, A \= 8, rule2(C).
rule2(C) :- empty(C), C \= 1, C \= 3, C \= 7, C \= 9.

done :- ordered_line(A, B, C), x(A), x(B), x(C), write('I won.'),


nl.
done :- all_full, write('Draw.'), nl.
getmove :- repeat, write('Please enter a move: '), read(x),
empty(x), assert(o(x)).
makemove :- move(X), !, assert(x(X)).
makemove :- all_full.
printsquare(N) :- o(N), write(' o ').
printsquare(N) :- x(N), write(' x ').
printsquare(N) :- empty(N), write(' ').
printboard :- printsquare(1), printsquare(2), printsquare(3), nl,
printsquare(4), printsquare(5), printsquare(6), nl,
printsquare(7), printsquare(8), printsquare(9), nl.
clear :- retractall(x(_)), retractall(o(_)).
% main

play :- random(1,11,P), (P >= 5), !, start.


play :- elsepart.
random_position(N) :- random(1,10,N).
elsepart :- clear, random_position(N), assert(x(N)), printboard,
repeat, getmove, respond.
%-----

start :- clear, repeat, getmove, respond.


respond :- ordered_line(A, B, C), o(A), o(B), o(C), printboard,
write('You won.'), nl.
respond :- makemove, printboard, done.

OUTCOME:
Implement of BFS for tic-tac-toe problem using PROLOG.

3.TSP USING HEURISTIC APPROACH:

OBJECTIVE:
Implementation of TSP using heuristic approach using
Java/LISP/Prolog

THEORY:
Firstly, let’s introduce the TSP model: a directed graph G=(V,
A), where V is the set of vertices (locations) to be visited, and
cᵢⱼ, (i,j) ∈ A is the cost (usually distance, or a literal dollar cost)
of each edge (the path between two locations). The objective of
the TSP is to find the lowest-cost route that satisfies the
problem’s four main constraints, specified below.
Constraints (1) and (2) tell us that each vertex j/i should
connect to/be connected to exactly another one vertex i/j.
However, these two constraints aren’t enough to guarantee that
the model’s result has only one circuit.
Thus we have constraint (3), which says that the final solution
cannot be a collection of smaller routes (or subtours) — the
model must output a single route that connects all the vertices.
Finally, constraint (4) defines a variable xᵢⱼ, setting it equal to 1
if two vertices (i, j) in the graph are connected as part of the
final tour, and 0 if not.

Heuristics and Problem Types


A good first step to an efficient solution is to get more specific
about exactly what kind of TSP you’re solving — different
heuristics may be better suited for some problems than others.
Based on whether or not cᵢⱼ=cⱼᵢ (i.e., if the cost of going from A
to B is the same as going from B to A), the TSP can be divided
into two general types: the symmetric TSP (STSP) and the
asymmetric TSP (ATSP).
The ATSP is usually related to intra-city problems. As city roads
are often diverse (one-way roads are a simple example), you
can’t assume that the best route from A to B has the same
properties (vehicle capacity, route mileage, traffic time, cost,
etc.) as the best route from B to A. By contrast, the STSP is
mostly for inter-city problems, usually with roughly symmetrical
roads. The best routes connecting two cities usually use the
same road(s) with only slightly different mileage (a difference
that can typically be ignored in the big picture).
Due to the different properties of the symmetric and asymmetric
variants of the TSP, we will discuss them separately below.
Heuristic for ATSP
One way to create an effective heuristic is to remove one or
more of the underlying problem’s constraints, and then modify
the solution to make it conform to the constraint after the fact,
or otherwise use it to inform your heuristic. There are two good
reasons why you might do so in the case of the TSP.
First, in general, constraints make an optimization problem
more difficult to solve. A problem’s final solution value can only
be the same or worse compared to the result of solving the
same problem with fewer constraints. Naturally, if we ignore
TSP’s third constraint (the most complicated one) to get an
initial result, the resultant objective value should be better than
the traditional solution.
Secondly, when we ignore constraint (3) in particular, it turns
out that the TSP actually becomes the mathematical model for
the assignment problem (AP). The assignment problem has the
property of integrality, meaning that we can substitute the
following for constraint (4):

Doing so makes the problem a linear program, which means it


can be solved far more quickly than its integer program
counterpart. In addition, it’s a P problem (rather than an NP
problem), which makes the solve process even faster. The
solution output by the assignment problem heuristic can serve
as the lower bound for our TSP solution. (This heuristic can be
used for both STSP and ATSP, but is usually better for the
ATSP given the symmetry-induced two-vertex subtours created
by the STSP.)

So now that we’ve explained this heuristic, let’s walk through an


example. Since we’ve eliminated constraint (3) (the subtour
elimination constraint), the assignment problem approach can
thus output multiple smaller routes instead of one big route.
The assignment problem’s solution (a collection of p directed
subtours C₁, C₂, …, Cₚ, covering all vertices of the directed
graph G) often must be combined to create the TSP’s heuristic
solution.

The algorithm for combining the AP’s initial result is as follows:


• Set C=C₁, C₂, …, Cₚ.
• - If p = 1, then stop — the current solution is the optimal
solution.
• - Otherwise, proceed to step 2.
• (Here, p is the number of subtours. If p = 1 (which means the
result has exactly one tour), that’s the optimal result for TSP.)
• Identify the two subtours Cₕ, Cₖ ∈ C with the most vertices.
• Merge Cₕ, Cₖ in a way that results in the smallest cost
increase. Then C has one fewer subtour, and p becomes p-1.
• - If p=1, then stop — the current solution is the feasible
solution for ATSP.
• - Otherwise, go back to step 2.

We can use a simple example here for further understanding


[2]. Assume there are six locations, and that the matrix below
shows the cost between each location pair.
Let’s say that the following is the optimal solution from the AP
model:

There are multiple subtours, so they must be combined via our


combination heuristic described above. First, we have to find
the top two subtours, then merge them with the smallest cost
increase (according to our above chart). The result looks like
this:
After this first round, there are no more subtours — just the
single tour that covers all vertices. Therefore we’re done!
(In this simple example, the initial AP result only had two
subtours, so we only needed to do a single merge. If there are
M subtours in the AP’s initial solution, we need to merge M-1
times.)

Heuristic for STSP — Nearest Neighbour

Assuming that the TSP is symmetric means that the costs of


traveling from point A to point B and vice versa are the same.
With this property in effect, we can use a heuristic that’s
uniquely suited for symmetrical instances of the problem. It’s
known as the nearest neighbor approach, as it attempts to
select the next vertex on the route by finding the current
position’s literal nearest neighbor.
It works as follows:
• Randomly select one vertex as the root.
• Find the vertex that is closest (more precisely, has the lowest
cost) to the current position but is not yet part of the route, and
add it into the route.
• Repeat until the route includes each vertex. See the following
graph and the description below for a detailed solution. (Ignore
the coloration of the lines for now.)

In the graph above, let’s say that we choose the leftmost node
as our root, and use the algorithm to guide us to a solution.
There are three nodes connected to our root node: the first
node from the right, the second node from the left, and the third
node from the left. They can each connect to the root with costs
1+∈, 1+∈, and 1, respectively (where ∈ is an infinitesimally
small positive value).
Following the nearest neighbor algorithm, we should add the
vertex with minimal cost, meaning the third node from the left
should be our choice. Step by step, this algorithm leads us to
the result marked by the red line in the graph, a solution with an
objective value of 10. However, we can see that going straight
down the line from left to right and connecting back around
gives us a better route, one with an objective value of 9+5∈.
Generalizing this observation, as the number of nodes involved
increases, the difference between the Nearest Neighbor result
and the optimal one will be infinite. However, when using
Nearest Neighbor for the examples in TSPLIB (a library of
diverse sample problems for the TSP), the ratio between the
heuristic and optimal results averages out to about 1.26, which
isn’t bad at all. Given its ease of implementation and the fact
that its results are solid, the Nearest Neighbor is a good, simple
heuristic for the STSP.
Outcome:
We Learn Introduced heuristics for the TSP, including
algorithms based on the Assignment Problem for the ATSP and
the Nearest Neighbor algorithm for the STSP. Both of these
algorithms are frequently used in practice for well-defined
problems.

PROGRAM:

class GFG
{

// Function to find the minimum weight

// Hamiltonian Cycle

static int tsp(int[][] graph, boolean[] v,

int currPos, int n,

int count, int cost, int ans)

// 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]);

return ans;

// 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 (int i = 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;

return ans;

// Driver code

public static void main(String[] args)

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

int n = 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 = new boolean[n];

// Mark 0th node as visited

v[0] = true;

int ans = 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);

}
}

OUTCOME:

4. HILL CLIMBING USING 8 PUZZLE PROBLEM:

OBJECTIVE:
Implementation of Hill-climbing to solve 8- Puzzle Problem

THEORY:
Hill Climb Algorithm
1. Hill Climbing is a heuristic search used for mathematical
optimization problems in the field of Artificial Intelligence. It is
an iterative algorithm that starts with an arbitrary solution to a
problem, then attempts to find a better solution by making an
incremental change to the solution.
2. So, given a large set of inputs and a good heuristic function,
the algorithm tries to find the best possible solution to the
problem in the most reasonable time period.
3. Solution is not necessary, a optimal solution (Global Optimal
Maxima) but it is consider to be good solution according to time
period.
4. Mathematical optimization problems: Implies that hill-
climbing solves the problems where we need to maximize or
minimize a given real function by choosing values from the
given inputs.
5. For example, hill climbing can be applied to the travelling
salesman problem.where we need to minimize the distance
traveled by the salesman.

Features of Hill Climb Algorithm


Generate and Test variant:
1. Generate possible solutions.
2. Test to see if this is the expected solution.
3. If the solution has been found quit else go to step 1.

Greedy approach:
Hill-climbing algorithm search moves in the direction which
optimizes the cost.

State Space Diagram for Hill Climb


The State-space diagram is a graphical representation of the
set of states(input) our search algorithm can reach vs the value
of our objective function (function we intend to
maximise/minimise). In which successive configurations or
states of an instance are considered, with the intention of
finding a goal state with a desired property.
Let's see how it look like
Local Maximum: Local maximum is a state which is better
than its neighbor states, But not necessarily the best in the
state space.
Global Maximum: This is the best solution in the entire search
space, where the objective function is the maximum.
Current State: The point where we are during the search is the
current state.
Flat local maximum: Where all the neighbor states of current
states have the same value.
Shoulder: It is a plateau region which has an uphill edge.
Ridges and alleys: It is region which is higher than its
neighbor’s but itself has a slope.

Types of Hill Climb Algorithm

Simple Hill Climb Algorithm


Simple hill climbing is the simplest way to implement a hill
climbing algorithm. It only evaluates the neighbor node state at
a time and selects the first one which optimizes current cost
and set it as a current state. It only checks it's one successor
state, and if it finds better than the current state, then move
else be in the same state.
features
• Less time consuming
• Less optimal solution and the
• solution is not guaranteed Steps involved in simple hill
climbing algorithm
Step 1: Evaluate the initial state, if it is goal state then return
success and Stop.
Step 2: Loop Until a solution is found or there is no new
operator left to apply.
Step 3: Select and apply an operator to the current state.
Step 4: Check new state:
If it is goal state, then return success and quit.
Else if it is better than the current state then assign new state
as a current state.
Else if not better than the current state, then return to step2.
Step 5: Exit.
Steepest-Ascent hill climbing
The steepest-Ascent algorithm is a variation of simple hill
climbing algorithm. This algorithm examines all the neighboring
node
s of the current state and selects one neighbor node which is
closest to the goal state. This algorithm consumes more time
as it searches for multiple neighbors.
Steps involved in Steepest-Ascent hill climbing algorithm
Step 1: Evaluate the initial state, if it is goal state then return
success and stop, else make the current state as your initial
state.
Step 2: Loop until a solution is found or the current state does
not change.
1.Let S be a state such that any successor of the current state
will be better than it.
2.For each operator that applies to the current state;
◦ Apply the new operator and generate a new state.
◦ Evaluate the new state.
◦ If it is goal state, then return it and quit, else compare it to the
S.
◦ If it is better than S, then set new state as S.
◦ If the S is better than the current state, then set the current
state to S.
Step 3: Exit
PROGRAM:

public class Main {

public static void main(String[] args) {

int startState[][] = {{6,2,5}, {1,8,0}, {7,4,3}}, goalState[][] =


{{7,6,5}, {8,0,4}, {1,2,3}};

System.out.println("Solving puzzle using DFS...");


DFS dfs = new DFS(startState, goalState);
dfs.search();
}
}
<pre>public class Node {
int state[][] = new int[3][3];

public Node() {
}

public Node(int state[][]) {


this.state = state;
}

public int getNum(int posX, int posY) {


return state[posX][posY];
}

public void setNum(int num, int x, int y) {


state[x][y] = num;
}
public int getX(int num) {
int positionX = 0;

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


for (int y = 0; y < 3; y++) {
if (state[x][y] == num) {
positionX = x;
break;
}
}
}

return positionX;
}

public int getY(int num) {


int positionY = 0;

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


for (int y = 0; y < 3; y++) {
if (state[x][y] == num) {
positionY = y;
break;
}
}
}

return positionY;
}

public void getCoordinate(int coordinate[], int num) {


for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
if (state[x][y] == num) {
coordinate[0] = x;
coordinate[1] = y;
break;
}
}
}
}

public void getState(int state[][]) {


state = this.state;
}

public String toString() {


String output = "";

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


for (int y = 0; y < 3; y++) {
output += state[x][y];
}
output += "\n";
}

return output;
}
}
<pre>import java.util.Stack;
import java.util.ArrayList;

public class DFS {


private int moveCounter = 0;
private Stack<Node> fringe = new Stack<Node>();
private Node startState, goalState, currentState = new
Node();
private ArrayList<Node> closed = new ArrayList<Node>();

public DFS(int start[][], int goal[][]) {


startState = new Node(start);
goalState = new Node(goal);
fringe.push(startState);
}

private void succesor(Node currentState) {


Node newState = new Node();
puzzle p = new puzzle();

newState = p.moveUp(currentState);

if (newState != null) {
fringe.push(newState);
}

newState = p.moveRight(currentState);

if (newState != null) {
fringe.push(newState);
}

newState = p.moveDown(currentState);

if (newState != null) {
fringe.push(newState);
}

newState = p.moveLeft(currentState);

if (newState != null) {
fringe.push(newState);
}
}

public void search() {


boolean found = false, exist = false, checkElement = true;
Node tmpNode = new Node();

currentState = fringe.pop();
closed.add(currentState);
succesor(currentState);

for (int x = 1; x < 2 ; x++) {


while (!found) {
try {
currentState = fringe.pop();

for (int i = 0; i < closed.size(); i++) {


tmpNode = closed.get(i);

if
(currentState.toString().equals(tmpNode.toString())) {
exist = true;
break;
}
}

if (!exist) {
moveCounter++;

if (currentState.getX(x) == goalState.getX(x) &&


currentState.getY(x) == goalState.getY(x)) {
found = true;
break;
}
else {
closed.add(currentState);
succesor(currentState);
}
}
}
catch (Exception e) {
System.out.println("No solutions found!");
break;
}
}
}
System.out.println("Number of step(s): " + moveCounter);
}
}
<pre>public class puzzle {
public void Puzzle() {
}

private void swap(Node newState, int newPosition[]) {


int emptyTile[] = new int[2], tmpNum;

newState.getCoordinate(emptyTile, 0);
tmpNum = newState.getNum(newPosition[0],
newPosition[1]);

newState.setNum(0, newPosition[0], newPosition[1]);


newState.setNum(tmpNum, emptyTile[0],
emptyTile[1]);
}

public Node moveUp(Node currentState) {


Node newState = new Node();
newState = null;
int newPosition[] = new int[2];

if (currentState.getX(0) - 1 >= 0) {
newState = currentState;
newPosition[0] = newState.getX(0) - 1;
newPosition[1] = newState.getY(0);

swap(newState, newPosition);
}

return newState;
}

public Node moveRight(Node currentState) {


Node newState = new Node();
newState = null;
int newPosition[] = new int[2];

if (currentState.getY(0) + 1 <= 2) {
newState = currentState;
newPosition[0] = newState.getX(0);
newPosition[1] = newState.getY(0) + 1;

swap(newState, newPosition);
}

return newState;
}

public Node moveDown(Node currentState) {


Node newState = new Node();
newState = null;
int newPosition[] = new int[2];

if (currentState.getX(0) + 1 <= 2) {
newState = currentState;
newPosition[0] = newState.getX(0) + 1;
newPosition[1] = newState.getY(0);

swap(newState, newPosition);
}

return newState;
}

public Node moveLeft(Node currentState) {


Node newState = new Node();
newState = null;
int newPosition[] = new int[2];

if (currentState.getY(0) - 1 >= 0) {
newState = currentState;
newPosition[0] = newState.getX(0);
newPosition[1] = newState.getY(0) - 1;

swap(newState, newPosition);
}

return newState;
}
}
OUTCOME:
5.MONKEY BANANA PROGRAM:

OBJECTIVE:
Implementation of Monkey Banana Problem using
LISP/PROLOG

THEORY:

In this prolog example, we will see one very interesting and


famous problem, The Monkey and Banana Problem.

Problem Statement
Suppose the problem is as given below –
• A hungry monkey is in a room, and he is near the door.
• The monkey is on the floor.
• Bananas have been hung from the center of the ceiling of the
room.
• There is a block (or chair) present in the room near the
window.
• The monkey wants the banana, but cannot reach it.

So how can the monkey get the bananas?


So if the monkey is clever enough, he can come to the block,
drag the block to the center, climb on it, and get the banana.
Below are few observations in this case –
• Monkey can reach the block, if both of them are at the same
level. From the above image, we can see that both the monkey
and the block are on the floor.
• If the block position is not at the center, then monkey can drag
it to the center.
• If monkey and the block both are on the floor, and block is at
the center, then the monkey can climb up on the block. So the
vertical position of the monkey will be changed.
• When the monkey is on the block, and block is at the center,
then the monkey can get the bananas.
Now, let us see how we can solve this using Prolog. We will
create some predicates as follows –
We have some predicates that will move from one state to
another state, by performing action.
• When the block is at the middle, and monkey is on top of the
block, and monkey does not have the banana (i.e. has not
state), then using the grasp action, it will change from has not
state to have state.
• From the floor, it can move to the top of the block (i.e. on top
state), by performing the action climb.
• The push or drag operation moves the block from one place to
another.
• Monkey can move from one place to another using walk or
move clauses.
Another predicate will be canget(). Here we pass a state, so
this will perform move predicate from one state to another using
different actions, then perform canget() on state 2. When we
have reached to the state ‘has>’, this indicates ‘has banana’.
We will stop the execution.
PROGRAM:
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),
push(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(Statel) :-
move(Statel,_,State2),
canget(State2).

OUTCOME:

You might also like