write a program monkey banana problem prolog
The Monkey and Banana Problem is a classic AI problem in Prolog, often used
to demonstrate state-space search and planning. The problem involves a
monkey in a room trying to get bananas hanging from the ceiling. The monkey
can walk, climb a box, and grab the bananas if it is positioned correctly.
Here's a Prolog program solving this problem using SWI-Prolog:
Monkey-Banana Problem in Prolog
% Define possible actions for the monkey
move(state(middle, on_box, middle, has_not), grasp, state(middle, on_box,
middle, has)).
move(state(Pos, on_floor, Pos, Has), climb, state(Pos, on_box, Pos, Has)).
move(state(Pos1, on_floor, Pos1, Has), push(Pos1, Pos2), state(Pos2, on_floor,
Pos2, Has)).
move(state(Pos1, on_floor, Box, Has), walk(Pos1, Pos2), state(Pos2, on_floor,
Box, Has)).
% Base case: Monkey has the banana
can_get(state(_, _, _, has)).
% Recursive case: Perform an action and continue
can_get(State1) :-
move(State1, _, State2),
can_get(State2).
Explanation
The state is represented as state(MonkeyPosition, MonkeyStatus,
BoxPosition, HasBanana).
o MonkeyPosition: left, middle, right
o MonkeyStatus: on_floor or on_box
o BoxPosition: left, middle, right
o HasBanana: has_not or has
The monkey can:
1. Walk from one position to another.
2. Push the box to another position.
3. Climb the box.
4. Grasp the banana when on the box at the right position.
Running the Program
To check if the monkey can get the banana from the initial state:
?- can_get(state(left, on_floor, left, has_not)).
If Prolog returns true, it means the monkey can successfully get the banana.
2. 8 puzzle program in prolog
The 8-Puzzle Problem is a classic AI search problem where we try to arrange
tiles in a 3×3 grid by sliding them into an empty space. The goal is to reach a
predefined target configuration.
Prolog Program for the 8-Puzzle Problem
This Prolog program implements a state-space search approach using Breadth-
First Search (BFS) or Depth-First Search (DFS).
Program Implementation (Using DFS)
% Define possible moves in the 8-puzzle
move([X, 0, Z, A, B, C, D, E, F], [0, X, Z, A, B, C, D, E, F]). % Move blank left
move([A, X, Z, 0, B, C, D, E, F], [0, X, Z, A, B, C, D, E, F]). % Move blank up
move([A, B, X, D, 0, F, G, H, I], [A, 0, X, D, B, F, G, H, I]). % Move blank left
move([A, B, C, D, X, F, 0, H, I], [A, B, C, 0, X, F, D, H, I]). % Move blank up
move([A, B, C, D, E, X, G, H, 0], [A, B, C, D, 0, X, G, H, E]). % Move blank left
move([A, B, C, D, E, F, G, X, 0], [A, B, C, D, E, 0, G, X, F]). % Move blank up
move([0, B, C, A, E, F, D, H, I], [A, B, C, 0, E, F, D, H, I]). % Move blank down
move([A, 0, C, D, B, F, G, H, I], [A, B, C, D, 0, F, G, H, I]). % Move blank down
move([A, B, C, D, 0, F, G, H, I], [A, 0, C, D, B, F, G, H, I]). % Move blank right
move([A, B, C, D, E, F, 0, H, I], [A, B, C, D, E, F, G, H, 0]). % Move blank right
move([A, B, C, D, E, F, G, H, 0], [A, B, C, D, E, 0, G, H, F]). % Move blank right
move([A, B, C, D, 0, F, G, H, I], [A, B, C, D, H, F, G, 0, I]). % Move blank down
% Solve the puzzle using depth-first search (DFS)
solve(State, Goal, [State]) :- State = Goal.
solve(State, Goal, [State | Path]) :-
move(State, NextState),
solve(NextState, Goal, Path).
% Wrapper to start solving
puzzle(Start, Goal, Solution) :-
solve(Start, Goal, Solution).
Explanation
1. State Representation:
o The puzzle is represented as a list of 9 elements (0 is the blank
space).
o Example initial state: [1, 2, 3, 4, 5, 6, 7, 8, 0] (solved state).
o Example unsolved state: [1, 2, 3, 4, 0, 5, 6, 7, 8].
2. Moves:
o The move/2 predicate defines how the blank tile (0) moves left,
right, up, or down.
3. Depth-First Search (DFS):
o The solve/3 predicate recursively finds a sequence of moves from
the initial state to the goal.
4. Running the Program:
?- puzzle([1, 2, 3, 4, 0, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8, 0], Solution).
3.n-queen problem program of prolog
The N-Queens Problem is a classic AI problem where the goal is to place N
queens on an N × N chessboard so that no two queens attack each other. This
means:
No two queens should be in the same row.
No two queens should be in the same column.
No two queens should be on the same diagonal.
Prolog Implementation of N-Queens Problem
% Solve the N-Queens problem
n_queens(N, Solution) :-
length(Solution, N), % Create a list of N elements
(each representing a queen's row position)
place_queens(Solution, N), % Place the queens safely
safe(Solution). % Ensure no two queens attack each other
% Generate valid positions for each queen
place_queens([], _).
place_queens([Q|Queens], N) :-
place_queens(Queens, N),
between(1, N, Q), % Q is a row position between 1 and N
not(attacks(Q, Queens, 1)). % Ensure it's not under attack
% Check if a queen is under attack
attacks(Q, [Q2|Queens], Dist) :-
Q2 =:= Q; % Same row
Q2 =:= Q + Dist; % Same diagonal (down-right)
Q2 =:= Q - Dist; % Same diagonal (up-right)
attacks(Q, Queens, Dist + 1). % Check next queen
attacks(_, [], _). % Base case: No more queens to check
% Ensure all queens are placed safely
safe([]).
safe([Q|Queens]) :-
safe(Queens),
not(attacks(Q, Queens, 1)).
% Run the program to solve for N queens
solve_n_queens(N, Solution) :-
n_queens(N, Solution),
print_solution(Solution, N).
% Print the chessboard representation
print_solution([], _).
print_solution([Q|Queens], N) :-
print_row(Q, N), nl,
print_solution(Queens, N).
print_row(Q, N) :-
forall(between(1, N, Col), (Col =:= Q -> write(' Q ') ; write(' . '))).
This program uses backtracking to find solutions.
How It Works
1. State Representation:
o Each solution is represented as a list of N elements, where each
value represents the row position of the queen in that column.
o Example for N=4: [2, 4, 1, 3] means:
Queen 1 is at row 2, column 1.
Queen 2 is at row 4, column 2.
Queen 3 is at row 1, column 3.
Queen 4 is at row 3, column 4.
2. Safe Placement:
o The attacks/3 predicate ensures no two queens share the same
row or diagonal.
3. Finding Solutions:
o n_queens/2 generates a valid solution list.
o solve_n_queens/2 calls the solver and prints the chessboard.
Running the Program
Run the following query in SWI-Prolog:
?- n_queens(8, Solution).
This finds a valid arrangement for 8-queens and prints the board
Example Output for N=4
. Q . .
. . . Q
Q . . .
. . Q .
Here, each Q represents a queen, and. represents an empty space.
4.Medical Diagnosis Expert System (Prolog)
This program uses facts and rules to diagnose diseases based on user input.
% Medical Diagnosis Expert System in Prolog
% Main predicate to start diagnosis
diagnose :-
write('Welcome to the Medical Diagnosis System!'), nl,
write('Please answer the following questions with yes or no.'), nl,
check_disease(Disease),
write('The diagnosis is: '), write(Disease), nl, !.
diagnose :-
write('Sorry, no disease matched the symptoms provided.'), nl.
% Knowledge Base: Rules for different diseases
check_disease(measles) :-
symptom(fever),
symptom(cough),
symptom(runny_nose),
symptom(conjunctivitis),
symptom(rash).
check_disease(chickenpox) :-
symptom(fever),
symptom(rash),
symptom(itching).
check_disease(mumps) :-
symptom(fever),
symptom(swollen_glands),
symptom(headache).
check_disease(common_cold) :-
symptom(fever),
symptom(runny_nose),
symptom(sore_throat),
symptom(sneezing).
check_disease(flu) :-
symptom(fever),
symptom(cough),
symptom(body_aches),
symptom(fatigue).
check_disease(strep_throat) :-
symptom(sore_throat),
symptom(fever),
symptom(swollen_lymph_nodes).
check_disease(dengue) :-
symptom(fever),
symptom(headache),
symptom(joint_pain),
symptom(skin_rash).
% Asking the user for symptoms dynamically
ask(Question) :-
write('Do you have '), write(Question), write('? (yes/no) '),
read(Response),
nl,
(Response == yes -> assert(symptom(Question)); fail).
% Clear previous symptoms before running a new diagnosis
clear_symptoms :- retractall(symptom(_)).
% Run the diagnosis system
start_diagnosis :-
clear_symptoms,
diagnose.
How It Works
1. User is asked about symptoms (e.g., "Do you have a fever?").
2. If a set of symptoms matches a disease, it provides a diagnosis.
3. If no disease matches, it informs the user.
4. Previous symptoms are cleared before a new diagnosis.
Running the Program in SWI-Prolog
?- start_diagnosis.
Example Interaction
Welcome to the Medical Diagnosis System!
Please answer the following questions with yes or no.
Do you have fever? (yes/no) yes
Do you have cough? (yes/no) yes
Do you have runny_nose? (yes/no) yes
Do you have conjunctivitis? (yes/no) yes
Do you have rash? (yes/no) yes
The diagnosis is: measles
5. Program to add two numbers in prolog
% Define a rule for addition
add(X, Y, Sum) :- Sum is X + Y.
% Example query:
% ?- add(5, 3, Result).
% Result = 8.
Explanation:
add(X, Y, Sum) :- Sum is X + Y.
This rule states that Sum is the result of adding X and Y.
When queried with ?- add(5, 3, Result)., Prolog calculates 5 + 3 and binds
Result to 8.
To run program write this:
?- add(5, 3, Result).
6. Program to categorise animal characteristics. in prolog
% Rules to classify animals based on characteristics
animal(lion) :- mammal, carnivore, has_mane.
animal(tiger) :- mammal, carnivore, has_stripes.
animal(elephant) :- mammal, herbivore, has_trunk.
animal(zebra) :- mammal, herbivore, has_stripes.
animal(eagle) :- bird, carnivore, has_talons.
animal(parrot) :- bird, herbivore, can_talk.
animal(crocodile) :- reptile, carnivore, has_scales.
% General classification rules
mammal :- has_hair, warm_blooded.
bird :- has_feathers, lays_eggs, warm_blooded.
reptile :- has_scales, cold_blooded.
% Sample facts about physical traits
has_hair.
has_feathers.
lays_eggs.
has_scales.
warm_blooded.
cold_blooded.
carnivore.
herbivore.
has_mane.
has_stripes.
has_trunk.
has_talons.
can_talk.
To run this program write
1) Find out if an animal is a lion
?- animal(lion).
2) Find an animal that is a bird and carnivorous:
?- animal(X), bird, carnivore.
?- mammal(tiger).
true.
?- animal(X).
X = lion ;
X = tiger ;
X = elephant ;
...
7. Program to read address of a person using compound
variable.
% Defining a structure for address
person(name(Name), address(Street, City, State, Country)).
% Rule to display the person's address
display_address(person(name(Name), address(Street, City, State, Country))) :-
write('Name: '), write(Name), nl,
write('Street: '), write(Street), nl,
write('City: '), write(City), nl,
write('State: '), write(State), nl,
write('Country: '), write(Country), nl.
Explanation:
The person/2 compound term represents a person with a name and
address.
The display_address/1 predicate extracts and prints the details.
You can query it with a specific person's details to display their address.
To run this program write:
?- display_address(person(name('Alice'), address('456 Elm St', 'Los
Angeles', 'CA', 'USA'))).
8.Program of fun to show concept of cut operator.
The cut operator (!) in Prolog is used to control backtracking by
preventing Prolog from reconsidering alternative rules once a cut is
encountered in a predicate.
Prolog Program: Using Cut (!)
% Define a fun/1 predicate with cut
fun(a) :- write('First rule: a'), nl, !.
fun(b) :- write('Second rule: b'), nl.
fun(c) :- write('Third rule: c'), nl.
% Example query:
% ?- fun(a).
% Output: First rule: a
% ?- fun(b).
% Output: Second rule: b
% ?- fun(a), fun(b), fun(c).
% Output:
% First rule: a
% Second rule: b
% Third rule: c
% Another example with cut affecting backtracking
fun2(x) :- write('Case 1: x'), nl, !.
fun2(x) :- write('Case 2: x'), nl. % This rule will never be reached
% Example query:
% ?- fun2(x).
% Output: Case 1: x
9.Program to count number of elements in a list .
% Base case: An empty list has a count of 0
count_elements([], 0).
% Recursive case: Count the head and process the tail
count_elements([_|Tail], Count) :-
count_elements(Tail, CountTail), % Recursively count elements in the tail
Count is CountTail + 1.
% Example Queries:
% ?- count_elements([a, b, c, d], Count).
% Count = 4.
Explanation:
1. Base Case:
o If the list is empty ([]), the count is 0.
2. Recursive Case:
o Ignore the head (_).
o Recursively count the elements in the tail (Tail).
o Add 1 to the count from the tail.
Example Queries and Output:
?- count_elements([1, 2, 3, 4, 5], Count).
Count = 5.
?- count_elements([], Count).
Count = 0.
?- count_elements([apple, orange, banana], Count).
Count = 3.
Topic: Built-in -function
Example: Check if a number is even, and list contains it
% Check if a number is even using built-in arithmetic
is_even(Number) :-
Remainder is Number mod 2,
Remainder =:= 0.
% Check if a number exists in a list and is even
even_member(Number, List) :-
member(Number, List),
is_even(Number).
% Get the length of a list using built-in function
list_length(List, Length) :-
length(List, Length).
% to run this program Example usage
% ?- is_even(4). Output: % true
% ?- even_member(6, [1,2,3,6,7]). Output: % true
% ?- list_length([a,b,c], L). Output: % L = 3
Common Built-in Predicates Used Here:
is/2: Evaluates the right-hand side as an arithmetic expression.
mod/2: Modulo operation.
=:=: Arithmetic equality.
member/2: Checks if an element is a member of a list.
length/2: Finds the length of a list.
Knowledge Base Operations with assert/1 and retract/1
Example: Dynamic Fact Update (e.g., storing symptoms)
% Declare dynamic predicate
:- dynamic symptom/1.
% Add a symptom to the knowledge base
add_symptom(S) :-
assert(symptom(S)).
% Remove a symptom
remove_symptom(S) :-
retract(symptom(S)).
% Show all symptoms
show_symptoms :-
findall(S, symptom(S), List),
write('Current symptoms: '), write(List), nl.
% Example:
% ?- add_symptom(fever). Output: true
% ?- add_symptom(cough). Output: true
% ?- show_symptoms. Output: Current symptoms: [fever,cough] true
Example: Write and Read Facts from a File
% Save current symptoms to a file
save_symptoms(File) :-
open(File, write, Stream),
forall(symptom(S), (write(Stream, symptom(S)), write(Stream, '.'), nl(Stream))),
close(Stream).
% Load symptoms from a file
load_symptoms(File) :-
open(File, read, Stream),
repeat,
read(Stream, Term),
( Term == end_of_file -> !, close(Stream)
; assert(Term), fail
).
% to run this program, Example:
% ?- save_symptoms('symptoms.pl'). output: true
% ?- load_symptoms('symptoms.pl'). output: true
Date/Time Using get_time/1, format_time/3
Example: Get Current Time
log_time :-
get_time(Stamp),
format_time(atom(TimeString), '%Y-%m-%d %H:%M:%S', Stamp),
write('Current time: '), write(TimeString), nl.
% Example:
% ?- log_time. Output: Current time: 2025-04-11 14:41:53 true.
Topic: Prolog List Operations
% Calculate the length of a list
list_length([], 0).
list_length([_|Tail], Length) :-
list_length(Tail, TailLength),
Length is TailLength + 1.
% Check if an element is a member of a list
is_member(Element, [Element|_]).
is_member(Element, [_|Tail]) :-
is_member(Element, Tail).
% Append two lists
append_lists([], List, List).
append_lists([Head|Tail], List, [Head|Result]) :-
append_lists(Tail, List, Result).
% Find the last element of a list
last_element([Element], Element).
last_element([_|Tail], Element) :-
last_element(Tail, Element).
To run this program
?- list_length([a, b, c, d], Length). output: Length = 4.
?- is_member(c, [a, b, c, d]). output: true.
?- append_lists([1, 2], [3, 4], Result). output: Result = [1, 2, 3, 4].
?- last_element([x, y, z], Last). output: Last = z.