prolog.final
prolog.final
parent(john, mary).
parent(john, david).
parent(susan, mary).
parent(susan, david).
parent(david, lily).
parent(lily, sam).
male(john).
male(david).
male(sam).
female(susan).
female(mary).
female(lily).
2a. This program defines basic arithmetic operations like addition, subtraction,
multiplication, and division.
% Addition
% Subtraction
% Multiplication
OUTPUT
2b. Factorial Calculation
factorial(0, 1).
factorial(N, Result) :-
N > 0,
N1 is N - 1,
factorial(N1, R1),
Result is N * R1.
OUTPUT
2c. Fibonacci sequence.
fibonacci(0, 0).
fibonacci(1, 1).
fibonacci(N, Result) :-
N > 1,
N1 is N - 1,
N2 is N - 2,
fibonacci(N1, R1),
fibonacci(N2, R2),
Result is R1 + R2.
OUTPUT
3.Write a program in prolog to solve Tower of Hanoi
N > 1,
M is N - 1,
OUTPUT
4.Prolog Program to Solve the 8-Puzzle Problem
% Define goal state
goal([1,2,3,4,5,6,7,8,0]).
move(State, NextState) :-
swap_position(ZeroPos, SwapPos),
I > 0, I1 is I - 1,
solve_8_puzzle(Start, Solution) :-
goal(State).
OUTPUT
5. Prolog Program to Solve the N-Queens Problem
n_queens(N, Solution) :-
range(1, N, Ns),
permutation(Ns, Solution),
safe(Solution).
Next is From + 1,
safe([]).
safe([Q | Others]) :-
safe(Others).
% Check diagonals
D1 is D + 1,
edge(a, b, 10).
edge(a, c, 15).
edge(a, d, 20).
edge(b, a, 10).
edge(b, c, 35).
edge(b, d, 25).
edge(c, a, 15).
edge(c, b, 35).
edge(c, d, 30).
edge(d, a, 20).
edge(d, b, 25).
edge(d, c, 30).
% Finding all paths from Start to other cities and returning to Start
distance(A, B, D),
Cost is Cost1 + D.
OUTPUT
7. Prolog Program to Solve the Water Jug Problem
% Empty Jug 1
% Empty Jug 2
Total is A + B,
Total is A + B,
goal(state(2, _)).
solve_water_jug(Start, Solution) :-
bfs([[Start]], Solution).
goal(State).
NewPaths),
bfs(NewQueue, Solution).
OUTPUT