0% found this document useful (0 votes)
38 views26 pages

Ada Lab Recordd New

The document contains 9 programming problems related to algorithms. Problem 1 involves finding the greatest common divisor (GCD) of two numbers using Euclid's algorithm and another algorithm. Problem 2 generates prime numbers within a given range using the Sieve of Eratosthenes algorithm. Problem 3 implements string matching using the brute force algorithm. Problems 4-6 involve sorting algorithms - merge sort, quicksort, and obtaining a minimum spanning tree using Prim's and Kruskal's algorithms. Problems 7-8 find shortest paths using Dijkstra's algorithm. Problem 9 computes binomial coefficients.

Uploaded by

Riyaz Shaik
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)
38 views26 pages

Ada Lab Recordd New

The document contains 9 programming problems related to algorithms. Problem 1 involves finding the greatest common divisor (GCD) of two numbers using Euclid's algorithm and another algorithm. Problem 2 generates prime numbers within a given range using the Sieve of Eratosthenes algorithm. Problem 3 implements string matching using the brute force algorithm. Problems 4-6 involve sorting algorithms - merge sort, quicksort, and obtaining a minimum spanning tree using Prim's and Kruskal's algorithms. Problems 7-8 find shortest paths using Dijkstra's algorithm. Problem 9 computes binomial coefficients.

Uploaded by

Riyaz Shaik
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/ 26

DATE: 5/10/20

PROGRAM NO:1
AIM:Write a program to find GCD of two numbers using different algorithms.
ALGORITHM:
• Euclid’s Algorithm:
Step 1: Let a, b be the two numbers
Step 2: a mod b = R
Step 3: Let a = b and b = R
Step 4: Repeat Steps 2 and 3 until a mod b is greater than 0
Step 5: GCD = b
Step 6: Finish
• Consecutive Integer Checking Algorithm:
Step 1: Check the minimum number (m, n) and assign the value to t
Step 2: Divide m by t, if the remainder of this division is zero go to step 3: otherwise go to
step 4.
Step 3: Divide n by t, if the division is zero return the value as answer and stop; otherwise
Proceedto step 4.
Step 4: Decrease the value of t by 1: go to step 2.
PROGRAM:
• Euclid's Algorithm:
def gcd(m,n):
while(n!=0):
rem=m%n
m=n
n=rem
return m
m=int(input("Enter the value of m:"))
n=int(input("Enter the value of n:"))
greatest_common_divisor=gcd(m,n)
print("The greatest common divisor is:",greatest_common_divisor)
•Consecutive Integer Checking Algorithm:
def gcdc(m,n):
t=min(m,n)
while t>0:
if m%t==0 and n%t==0:
return t
t=t-1
m = int(input("Enter First number: "))
n = int(input("Enter Second number: "))
print("The Greatest Common Divisor is:",gcdc(m,n))20CSl57

1
PROGRAM NO:2
DATE: 5/10/20
AIM: Write a program to Implement Sieve of Eratosthenes to generate Prime Numbers Between
Given Range.
ALGORITHM:
•Sieve of Eratosthenes Algorithm:
Step1: For all numbers m: 2 ... n, if m is unmarked:
• Add m to primes list;
• Mark all its multiples, lesser or equal, then n (k * m ≤ n, k ≥ 2);
Step2: Otherwise, if m is marked, then it is a composite number.
PROGRAM:
import math
num=int(input("Enter the number\n"));
prime=[]
for i in range(2,num+1):
prime.append(i)
i=2
while(i<=int(math.sqrt(num+1))):
if i in prime:
for j in range(i*2,num+1,i):
if j in prime:
prime.remove(j)
i=i+1
print(prime)

2
PROGRAM NO:3
DATE: 12/10/20
AIM:Write a program to implement string matching using Brute force.
ALGORITHM:
•NAIVE-STRING-MATCHER (T, P)
Step1. n ← length [T]
Step2. m ← length [P]
Step3. for s ← 0 to n -m
Step4. do if P [1......m] = T [s + 1....s + m]
Step5. then print "Pattern occurs with shift" s
PROGRAM:
def search(pat,txt):
M = len(pat)
N = len(txt)
for i in range(N -M + 1):
j=0
while(j < M):
if (txt[i + j] != pat[j]):
break
j += 1
if (j == M):
print("Pattern found at index ", i)
txt = input("Enter the text:")
pat = input("Enter the pattern:")
search(pat, txt)

3
PROGRAM NO:4
DATE: 12/10/20
AIM:Write a program to implement Merge Sort.
ALGORITHM:
•Merge-Sort (numbers [], p, r)
if p < r then
q = ⌊(p + r) / 2⌋
Merge-Sort (numbers [], p, q)
Merge-Sort (numbers [], q + 1, r)
Merge (numbers [], p, q, r)
•Function: Merge (numbers [], p, q, r)
n1 = q –p + 1
n2 = r –q
declare leftnums [1…n1 + 1] and rightnums [1…n2 + 1] temporary arrays
for i = 1 to n1
leftnums[i] = numbers [p + i -1]
for j = 1 to n2
rightnums[j] = numbers [q+ j]
leftnums [n1 + 1] = ∞
rightnums [n2 + 1] = ∞
i=1
j=1
for k = p to r
if leftnums[i] ≤ rightnums[j]
numbers[k] = leftnums[i]
i=i+1
else
numbers[k] = rightnums[j]
j=j+1
PROGRAM:
def mergeSort(nlist):
print("splitting: ",nlist)
if(len(nlist)>1):
mid=len(nlist)//2;
lefthalf=nlist[:mid]
righthalf=nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
merge(nlist,lefthalf,righthalf)
def merge(nlist,lefthalf,righthalf):
i=j=k=0 #i=lefthalf #j=righthalf #k=index
while(i<len(lefthalf) and j<len(righthalf)):
if(lefthalf[i]<righthalf[j]):
nlist[k]=lefthalf[i] #copy into main list
i=i+120CSl57

4
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
while(i<len(lefthalf)):#remaining elements
nlist[k]=lefthalf[i]
i=i+1
k=k+1
while(j<len(righthalf)):
nlist[k]=righthalf[j]
j=j+1
k=k+1
#print("merging: ",nlist)
nlist=[]
n=int(input("enter the size\n"))
for i in range(0,n):
ele=int(input("enter number\n"))
nlist.append(ele)
print(nlist)
mergeSort(nlist)
print(nlist)

5
PROGRAM NO:5
DATE: 19/10/20
AIM:Write a program to implement Quick Sort.
ALGORITHM:
• Quick Sort Algorithm:
QUICKSORT (array A, int m, int n)
Step1. if (n > m)
Step2. then
Step3. i ← a random index from [m, n]
Step4. swap A [i] with A[m]
Step5. o ← PARTITION (A, m, n)
Step6. QUICKSORT (A, m, o -1)
Step7. QUICKSORT (A, o + 1, n)
• Partition Algorithm:
PARTITION (array A, int m, int n)
Step1. x ← A[m]
Step2. o ← m
Step3. for p ← m + 1 to n
Step4. do if (A[p] < x)
Step5. then o ← o + 1
Step6. swap A[o] with A[p]
Step7. swap A[m] with A[o]
Step8. return o
PROGRAM:
n = int(input("How many elements do you want to add? "))
Array = []
print("Enter the elements of the list: ")
for i in range(n):
Array.append(input())
print (Array)
low = 0
up = len(Array) -1
def partition(Array,low,up):
i = low+1
j = up
pivot = Array[low]
while(i<=j):
while(Array[i]<=pivot and i<up):
i = i+1
while(Array[j]>pivot):
j = j-1
if(i<j):
Array[i],Array[j] = Array[j],Array[i]
i = i+1
j = j-120CSl57

6
else:
i = i+1
Array[low] = Array[j]
Array[j] = pivot
return j
def quick(Array,low,up):
if(low>=up):
return
piv_loc = partition(Array,low,up)
quick(Array,low,piv_loc-1)
quick(Array,piv_loc+1,up)
quick(Array,low,up)
print(Array)

7
PROGRAM NO:6
DATE: 19/10/20
AIM:Write a program to obtain minimum cost spanning tree using Prim’s Algorithm.
ALGORITHM:
Step 1: Select a starting vertex.
Step 2: Repeat Steps 3 and 4 until there are fringe vertices.
Step 3: Select an edge e connecting the tree vertex and fringe vertex that has minimum
weight.
Step 4: Add the selected edge and the vertex to the minimum spanning tree T.
[END OF LOOP]
Step 5: EXIT
PROGRAM:
INF = 9999999
V=5
G = [[0, 9, 75, 0, 0],
[9, 0, 95, 19, 42],
[75, 95, 0, 51, 66],
[0, 19, 51, 0, 31],
[0, 42, 66, 31, 0]]
selected = [0, 0, 0, 0, 0]
no_edge = 0
selected[0] = True
print("Edge : Weight\n")
while (no_edge < V -1):
minimum = INF
x=0
y=0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i][j]):
if minimum > G[i][j]:
minimum = G[i][j]
x=i
y=j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1

8
9
PROGRAM NO:7
DATE: 9/11/20
AIM:Write a program to obtain minimum cost spanning tree using Kruskal’s Algorithm.
ALGORITHM:
Step 1: Create a forest in such a way that each graph is a separate tree.
Step 2: Create a priority queue Q that contains all the edges of the graph.
Step 3: Repeat Steps 4 and5 while Q is NOT EMPTY
Step 4: Remove an edge from Q
Step 5: IF the edge obtained in Step 4 connects two different trees, then Add it to the forest
(for combining two trees into one tree).
ELSE
Discard the edge.
Step 6: END
PROGRAM:
class Graph:
def __init__(self,vertices):
self.V = vertices
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
# Search function
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def apply_union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
# Applying Kruskal algorithm
def kruskal_algo(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):20CSl57

10
parent.append(node)
rank.append(0)
while e < self.V -1:
u, v, w = self.graph[i]
i=i+1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e=e+1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
for u, v, weight in result:
print("%d -%d: %d" % (u, v, weight))
g = Graph(6)
g.add_edge(0, 1, 4)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 2)
g.add_edge(1, 0, 4)
g.add_edge(2, 0, 4)
g.add_edge(2, 1, 2)
g.add_edge(2, 3, 3)
g.add_edge(2, 5, 2)
g.add_edge(2, 4, 4)
g.add_edge(3, 2, 3)
g.add_edge(3, 4, 3)
g.add_edge(4, 2, 4)
g.add_edge(4, 3, 3)
g.add_edge(5, 2, 2)
g.add_edge(5, 4, 3)
g.kruskal_algo()

11
PROGRAM NO:8
DATE: 9/11/20
AIM:Write a program to obtain shortest path using Djikstra’salgorithm.
ALGORITHM:
Step 1: Create a set shortPath to store vertices that come in the way of the shortest path
tree.
Step 2: Initialize all distance values as INFINITE and assign distance values as 0 for source
Vertex.Sothat it is picked first.
Step 3: Loop until all vertices of the graph are in the shortPath.
Step 3.1: Take a new vertex that is not visited and is nearest.
Step 3.2: Add this vertex to shortPath.
Step 3.3: Forall adjacent vertices of this vertex update distances. Now check every
adjacent vertexof V, if sum of distance of u and weight of edge is less the
update it.
PROGRAM:
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print ("Vertex Distance from Source")
for node in range(self.V):
print (node, "t", dist[node])
def minDistance(self, dist, sptSet):
# Initilaize minimum distance for next node
min = sys.maxsize
# Search not nearest vertex not in the
# shortest path tree
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
def dijkstra(self, src):
dist = [sys.maxsize] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
u = self.minDistance(dist, sptSet)
sptSet[u] = True
for v in range(self.V): 20CSl57

12
if self.graph[u][v] > 0 and sptSet[v] == False andist[v] >dist[u]+self.graph[u][v]:
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
];
g.dijkstra(0);

13
PROGRAM NO:9
DATE: 23/11/20
AIM:Write a program to compute Binomial Coefficient.
ALGORITHM:
Step 1: declare function for binomial coefficient table
int bin_table (int val)
Loop for int i = 0 and i <= val and i++
print i
Declare int num = 1
Loop for int j = 0 and j <= i and j++
If (i! = 0 && j! = 0)
set num = num * (i -j + 1) / j
End
print num
End
print \n
Step 2:In main ()
Declare int value = 5
call bin_table(value)
PROGRAM:
defbinomialCoeff(n , k):
if k > n :
return 0
if k==0 or k ==n :
return 1
return binomialCoeff(n-1 , k-1) + binomialCoeff(n-1 , k)
n=5
k=2
print ("Value of C(%d,%d) is (%d)" %(n , k , binomialCoeff(n , k)))

14
PROGRAM NO:10
DATE: 23/11/20
AIM:Write a program to obtain shortest path using Floyds algorithms.
ALGORITHM:
• FLOYD -WARSHALL (W)
Step1. n ← rows [W].
Step2. D0 ← W
Step3. for k ← 1 to n
Step4. do for i ← 1 to n
Step5. do for j ← 1 to n
Step6. do dij(k)← min (dij(k-1),dik(k-1)+dkj(k-1))
Step7. return D(n)
PROGRAM:
def printSolution(dist, N):
for i in range(N):
for j in range(N):
if(dist[i][j] == M):
print("INF", end=" ")
else:
print(dist[i][j], end=" ")
print(" ")
def floyd(adjMatrix, N):
dist = adjMatrix.copy()
for k in range(N):
for v in range(N):
for u in range(N):
if dist[v][k] != float('inf') and dist[k][u] != float('inf') and (dist[v][k] + dist[k][u] <dist[v][u]):
dist[v][u] = dist[v][k] + dist[k][u]
if dist[v][v] < 0:
print("Negative Weight Cycle Found")
return
printSolution(dist, N)
if __name__ == '__main__':
N = 4 #no of vertices in the graph
M = float('inf')
adjMatrix = [
[0, M, 3, M],
[2, 0, M, M],
[M, 7, 0, 1],
[6, M, M, 0]
]
floyd(adjMatrix, N)20CSl57

15
16
PROGRAM NO:11
DATE: 30/11/20
AIM:Write a program to compute Transitive closure using Warshall’salgorithm.
ALGORITHM:
Warshall (A [1...n, 1...n])
Implements Warshall's algorithm for computing the transitive closure //Input: The adjacency matrix A
of a digraph with n vertices //Output: The transitive closure ofthe digraph RO<A
for k<--1 to n do
for i <--1 to n do
for j <--1 to n do
R(k)[i. i] <--R(k-1) [i. j] or (R(k-1) [i. k] and R(k-1)[k. j])
Return R(n)
PROGRAM:
class Graph:
def __init__(self, vertices):
self.V = vertices
def printSolution(self, reach):
print ("Following matrix transitive closure of the given graph ")
for i in range(self.V):
for j in range(self.V):
print ("%7d\t" %(reach[i][j]))
print ("")
def transitiveClosure(self,graph):
reach =[i[:] for i in graph]
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j])
self.printSolution(reach)
g= Graph(4)
graph = [[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0],
[1, 0, 1, 0]]
g.transitiveClosure(graph)20CSl57

17
18
PROGRAM NO:12
DATE: 30/11/20
AIM:Write a program to implement Breadth First search.
ALGORITHM:
Step1: Start by putting any one of the graph's vertices at the back of a queue.
Step2: Take the front item of the queue and add it to the visited list.
Step3: Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited
list tothe back of the queue.
Step4: Keep repeating steps 2 and 3 until the queue is empty.
PROGRAM:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def BFS(self, s):
visited = [False] * (max(self.graph) + 1)
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
print(s, end=" ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is Breadth First Traversal"
" (starting from vertex 2)")
g.BFS(2)

19
PROGRAM NO:13
DATE: 7/12/20
AIM:Write a program to implement Depth First search.
ALGORITHM:
Step1: Create a recursive function that takes the index of node and a visited array.
Step2: Mark the current node as visited and print the node.
Step3: Traverse all the adjacent and unmarked nodes and call the recursive function with
index ofadjacent node.
PROGRAM:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited.add(v)
print(v, end=' ')
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)
def DFS(self, v):
visited = set()
self.DFSUtil(v, visited)
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is DFS from (starting from vertex 2)")
g.DFS(2)

20
PROGRAM NO:14
DATE: 14/12/20
AIM:Write a program to implement Topological sorting.
ALGORITHM:
Step1: In DFS, start from a vertex, first print it and then recursively call DFS for its
adjacent vertices. Intopological sorting, we use a temporary stack.
Step2: Don’t print the vertex immediately, first recursively call topological sorting for all
its adjacentvertices, then push it to a stack.
Step3: Finally, print contents of the stack. Note that a vertex is pushed to stack only when
all of itsadjacent vertices (and their adjacent vertices and so on) are already in the
stack.
PROGRAM:
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self, u, v):
self.graph[u].append(v)
def topologicalSort(self):
in_degree = [0]*(self.V)
for i in self.graph:
for j in self.graph[i]:
in_degree[j] += 1
queue = []
for i in range(self.V):
if in_degree[i] == 0:
queue.append(i)
cnt = 0
top_order = []
while queue:
u = queue.pop(0)
top_order.append(u)
for i in self.graph[u]:
in_degree[i] -= 1
if in_degree[i] == 0:
queue.append(i)
cnt += 1
if cnt != self.V:
print ("There exists a cycle in the graph")
else :
# Printtopological order
print (top_order)
g = Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0); 20CSl57

21
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
print ("Following is a Topological Sort of the given graph")
g.topologicalSort()

22
PROGRAM NO:15
DATE: 21/12/20
AIM:Write a program to implement Subset Sum Problem Backtracking.
ALGORITHM:
subSetSum (set, subset, n, subSize, total, node, sum)
if total = sum, then
display the subset
//go for finding next subset
subSetSum (set, subset, , subSize-1, total-set[node], node+1, sum)
return
else
for all element i in the set, do
subset[subSize] := set[i]
subSetSum (set, subset, n, subSize+1, total+set[i], i+1, sum)
done
PROGRAM:
def isSubsetSum(set, n, sum):
if (sum == 0):
return True
if (n == 0 and sum != 0):
return False
if (set[n -1] > sum):
return isSubsetSum(set, n -1, sum);
return isSubsetSum(set, n -1, sum) or isSubsetSum(set, n -1, sum -set[n -1])
set = [3, 34, 4, 12, 5, 2]
sum = 9
n = len(set)
if (isSubsetSum(set, n, sum) == True):
print("Found a subset with given sum")
else:
print("No subset with given sum")

23
PROGRAM NO:16
DATE: 21/12/20
AIM:Write a program to implement N Queens problem using Backtracking.
ALGORITHM:
Step1: Start in the leftmost column
Step2: If all queens are placed
return true
Step3: Try all rows in the current column.
Do following for every tried row.
1. If the queen can be placed safely in this rowthen mark this [row, column] as partof thesolution and
recursively check if placingqueen here leads to a solution.

2. If placing the queen in [row, column] leads toa solution then returns true.
3. If placing queen doesn't lead to a solution, thenunmark this [row, column]
(Backtrack)and go tostep (a) to try other rows.
Step4: If all rows have been tried and nothing worked,return false to trigger backtracking.
PROGRAM:
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j], end = " ")
print()
def isSafe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, -1, -1),
range(col, -1, -1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, N, 1),
range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solveNQUtil(board, col):
if col >= N:
return True
for i in range(N):
if isSafe(board, i, col): 20CSl57

24
board[i][col] = 1
if solveNQUtil(board, col + 1) == True:
return True
board[i][col] = 0
return False
def solveNQ():
board=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
]
If solveNQuntil(board,0)==False:
Print(“sol not there”)
Return false
Printsolution (board)
Return true
solveNQ()

25
26

You might also like