0% found this document useful (0 votes)
9 views10 pages

AI LAB (1)

AI lab file

Uploaded by

Ayush Fsf
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)
9 views10 pages

AI LAB (1)

AI lab file

Uploaded by

Ayush Fsf
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/ 10

Experiment - 1

AIM - Implementation of Water Jug Problem

CODE:
from collections import deque
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
public class Solution {
public static void main(String[] args) {
int jug1 = 4, jug2 = 3, target = 2;
System.out.println("Path from initial state to solution state ::");
solve(jug1, jug2, target);}
public static void solve(int a, int b, int target) {
HashMap<String, Integer> m = new HashMap<>();
boolean isSolvable = false;
Deque<int[]> q = new ArrayDeque<>();
int[][] path = new int[1000][2];
int pathIndex = 0;

q.offer(new int[]{0, 0});

while (!q.isEmpty()) {
int[] u = q.poll();
if (m.containsKey(u[0] + " " + u[1])) continue;
if (u[0] > a || u[1] > b || u[0] < 0 || u[1] < 0) continue;
path[pathIndex++] = u;
m.put(u[0] + " " + u[1], 1);
if (u[0] == target || u[1] == target) {
isSolvable = true;
if (u[0] == target) {
if (u[1] != 0) path[pathIndex++] = new int[]{u[0], 0};
} else {
if (u[0] != 0) path[pathIndex++] = new int[]{0, u[1]};
}
for (int i = 0; i < pathIndex; i++) {
System.out.println("(" + path[i][0] + ", " + path[i][1] + ")");
}
break;}
q.offer(new int[]{a, u[1]}); // Fill Jug1
q.offer(new int[]{u[0], b}); // Fill Jug2

for (int ap = 0; ap <= Math.max(a, b); ap++) {


int c = u[0] + ap;
int d = u[1] - ap;
if (c == a || (d == 0 && d >= 0)) {
q.offer(new int[]{c, d});
}
c = u[0] - ap;
d = u[1] + ap;
if ((c == 0 && c >= 0) || d == b) {
q.offer(new int[]{c, d});}}
q.offer(new int[]{a, 0});
q.offer(new int[]{0, b});
}if (!isSolvable) {
System.out.println("Solution not possible");}}}

OUTPUT:
Experiment - 2

AIM - Introduction to Lisp, and basic programming in LISP like following:

1. Write a LISP function to compute the sum of squares.


(defun sum-of-squares (lst)
(reduce #'+
(mapcar (lambda (x) (* x x))
lst)))

(print (sum-of-squares '(1 2 3 4 5)))

2. Write a LISP function to compute the difference of squares. (if x > y return x2 – y2,
Otherwise y2 – x2).
(defun difference-of-squares (x y)
(let ((x-squared (* x x))
(y-squared (* y y)))
(if (> x y)
(- x-squared y-squared)
(- y-squared x-squared))))

(print (difference-of-squares 5 3))


(print (difference-of-squares 3 5))

3. Write a Recursive LISP function which takes one argument as a list and returns the
last element of the list. (Do not use the last predicate.)
(defun last-element (lst)
(if (null (cdr lst)) ;
(car lst) ;
(last-element (cdr lst)))) ;

(print (last-element '(1 2 3 4 5)))


(print (last-element '(a b c d e)))

4. Write a Recursive LISP function which takes one argument as a list and return list
except the last element of the list. (Do not use butlast.)
(defun remove-last (lst)
"Recursively remove the last element of the list lst."
(if (null (cdr lst)) ; Check if cdr (rest) of the list is empty
'() ; If it is, return an empty list (since there's no element to remove)
(cons (car lst) ; Otherwise, cons the car (first element) of the list
(remove-last (cdr lst))))) ; with the result of recursively removing the last element
(print (remove-last '(1 2 3 4 5)))
(print (remove-last '(a b c d e)))

5. Write a Recursive LISP function which takes one argument as a list and returns the
reverse of the list. (Do not use reverse predicate).
(defun reverse-list (lst)
(if (null lst) ; If the list is empty
'() ; Return an empty list
(append (reverse-list (cdr lst)) ; Recursively reverse the rest of the list
(list (car lst))))) ; Append the first element to the reversed list
(print (reverse-list '(1 2 3 4 5)))
(print (reverse-list '(a b c d e)))
6. Write a Recursive LISP function which takes two arguments first an atom second a
list returns a list after removing the first occurrence of that atom within the list.
(defun remove-first-occurrence (atom lst)
"Recursively remove the first occurrence of atom within the list lst."
(cond ((null lst) '()) ; Base case: if the list is empty, return an empty list
((equal atom (car lst)) (cdr lst)) ; If the first element of the list is equal to the atom, skip it by
returning the rest of the list
(t (cons (car lst) ; Otherwise, cons the first element of the list
(remove-first-occurrence atom (cdr lst)))))) ; with the result of recursively removing the atom
from the rest of the list

(print (remove-first-occurrence 'b '(a b c d e)))


(print (remove-first-occurrence '3 '(1 2 3 4 3 5)))

7. Write a Recursive LISP function which appends two lists together.


(defun append-lists (list1 list2)
"Recursively appends two lists together."
(if (null list1) ; If the first list is empty
list2 ; Return the second list
(cons (car list1) ; Otherwise, cons the first element of the first list
(append-lists (cdr list1) list2)))) ; with the result of recursively appending the rest of the first list to
the second list

(print (append-lists '(1 2 3) '(4 5 6)))


(print (append-lists '(a b c) '(d e f)))
8. Write a recursive LISP function which takes 2 lists as arguments and returns a list
containing alternate elements from each list.
(defun alternate-elements (list1 list2)
"Recursively returns a list containing alternate elements from list1 and list2."
(cond ((null list1) list2) ; If list1 is empty, return list2
((null list2) list1) ; If list2 is empty, return list1
(t (cons (car list1) ; Cons the first element of list1
(cons (car list2) ; Cons the first element of list2
(alternate-elements (cdr list1) (cdr list2))))))) ; Recur with the rest of both lists

(print (alternate-elements '(1 3 5) '(2 4 6)))


(print (alternate-elements '(a c e) '(b d f)))
Experiment - 3

1. Write a function that compute the factorial of a number (factorial of 0 is 1, and


factorial of n is n*(n-1)*...1. Factorial is defined only for integers greater than or
equal to 0.)

(defun factorial (n)


(if (< n 0)
(error "Factorial is defined only for integers greater than or equal to 0.")
(if (= n 0)
1
(* n (factorial (- n 1))))))

;; Example usage
(format t "Factorial of 5 is ~a" (factorial 5))

2. Write a function that evaluates a fully parenthesized infix arithmetic expression. For
examples, (infix (1+ (2*3))) should return 7.

3. Write a function that performs a depth first traversal of a binary tree. The function
should return a list containing the tree nodes in the order they were visited.
(defstruct binary-tree
value
left
right)

(defun depth-first-traversal (tree)


(if (null tree)
nil
(append (list (binary-tree-value tree))
(depth-first-traversal (binary-tree-left tree))
(depth-first-traversal (binary-tree-right tree)))))

(defvar example-tree
(make-binary-tree :value 'A
:left (make-binary-tree :value 'B
:left (make-binary-tree :value 'D)
:right (make-binary-tree :value 'E))
:right (make-binary-tree :value 'C
:left (make-binary-tree :value 'F)
:right (make-binary-tree :value 'G))))

(format t "Depth-first traversal: ~a" (depth-first-traversal example-tree))

4. Write a LISP program for water jug problem.

5. Write a LISP program that determines whether an integer is prime.


(defun is-prime (n)
(cond
((<= n 1) nil) ; 0 and 1 are not prime
((= n 2) t) ; 2 is prime
((evenp n) nil) ; All other even numbers are not prime
(t (not (loop for i from 3 to (isqrt n) by 2
until (zerop (mod n i))
finally (return t))))))

;; Example usage
(format t "Is 17 prime? ~a" (is-prime 17))
(format t "Is 25 prime? ~a" (is-prime 25))
Experiment - 4

Refer following figure as map with distance details, Write a program in your
preferred language to generate path from ARAD to BUCHREST, analyze result
obtained by
a) Depth First Search
b) Breadth First Search
c) Uniform Cost Search

from collections import deque

# Define the graph as a dictionary where keys are city names and values are lists of adjacent cities and their
distances
graph = {
'Arad': [('Zerind', 75), ('Timisoara', 118), ('Sibiu', 140)],
'Zerind': [('Oradea', 71), ('Sibiu', 151)],
' Oradea': [],
'Timisoara': [('Lugoj', 70)],
'Lugoj': [('Mehadia', 75)],
'Mehadia': [('Drobeta', 75)],
'Drobeta': [('Craiova', 120)],
'Sibiu': [('Fagaras', 99), ('Rimnicu Vilcea', 80), ('Pitesti', 97)],
'Fagaras': [('Bucharest', 211)],
'Rimnicu Vilcea': [('Pitesti', 90), ('Craiova', 146)],
'Pitesti': [('Bucharest', 101)],
'Craiova': [('Giurgiu', 98)],
'Giurgiu': [('Bucharest', 86)],
}

# Function to implement depth-first search


def depth_first_search(graph, start, goal):
stack = [(start, [])]
visited = set()
while stack:
(vertex, path) = stack.pop()
if vertex not in visited:
visited.add(vertex)
path.append(vertex)
if vertex == goal:
return path
for neighbor, distance in graph[vertex]:
stack.append((neighbor, path[:]))
return None

# Function to implement breadth-first search


def breadth_first_search(graph, start, goal):
queue = deque([(start, [])])
visited = set()
while queue:
(vertex, path) = queue.popleft()
if vertex not in visited:
visited.add(vertex)
path.append(vertex)
if vertex == goal:
return path
for neighbor, distance in graph[vertex]:
queue.append((neighbor, path[:]))
return None

# Function to implement uniform-cost search


def uniform_cost_search(graph, start, goal):
priority_queue = [(0, start, [])]
visited = set()
while priority_queue:
(cost, vertex, path) = priority_queue.pop(0)
if vertex not in visited:
visited.add(vertex)
path.append(vertex)
if vertex == goal:
return path
for neighbor, distance in graph[vertex]:
new_cost = cost + distance
priority_queue.append((new_cost, neighbor, path[:]))
priority_queue.sort(key=lambda x: x[0]) # Sort by cost
return None

# Find paths using DFS, BFS, and UCS


dfs_path = depth_first_search(graph.copy(), 'Arad', 'Bucharest')
bfs_path = breadth_first_search(graph.copy(), 'Arad', 'Bucharest')
ucs_path = uniform_cost_search(graph.copy(), 'Arad', 'Bucharest')

# Print the paths


print("Depth-first search path:", dfs_path if dfs_path else "No path found")
print("Breadth-first search path:", bfs_path if bfs_path else "No path found")
print("Uniform-cost search path:", ucs_path if ucs_path else "No path found")

Output:

You might also like