22BDS0212 DAA Assignment 2
22BDS0212 DAA Assignment 2
Subject Name with code: Design and Analysis of Algorithm Lab – BCSE204P
Assessment No.: 02
Date of Submission: 18/02/2024
Aim: - The objective of this assessment is to analyse 2 divide and conquer algorithms-
Maximum Sub-Array and Karatsuba Algorithm – and 4 Dynamic Programming algorithms-
Matrix Chain multiplication, Longest Common subsequence, Assembly Line Scheduling and
0/1 Knapsack
Pseudocode: -
Code: -
1)Dynamic Programming: -
a)Assembly Line Scheduling : -
def
time_scheduling(station_time,switch_time,curr_line,curr_station,exit1,exit2,n)
:
if curr_station == n-1:
if curr_line == 0:
return exit1
else:
return exit2
same =
time_scheduling(station_time,switch_time,curr_line,curr_station+1,exit1,exit2,
n) + station_time[curr_line][curr_station+1]
diff = time_scheduling(station_time,switch_time,not
curr_line,curr_station+1,exit1,exit2,n) + station_time[not
curr_line][curr_station+1] + switch_time[curr_line][curr_station+1]
return min(same,diff)
n = 4
a = [[4, 5, 3, 2], [2, 10, 1, 4]]
t = [[0, 7, 4, 5], [0, 9, 2, 8]]
e1 = 10
e2 = 12
x1 = 18
x2 = 7
x = time_scheduling(a, t, 0, 0, x1, x2, n) + e1 + a[0][0]
y = time_scheduling(a, t, 1, 0, x1, x2, n) + e2 + a[1][0]
print(f'The minimum time required to complete the task is: {min(x, y)}')
Output: -
b)Karatsuba Algorithm: -
def karatsuba(x,y):
if x<10 or y<10:
return x*y
else:
n=max(len(str(x)),len(str(y)))
half=n//2
a=x//(10**(half))
b=x%(10**(half))
c=y//(10**(half))
d=y%(10**(half))
ac = karatsuba(a,c)
bd = karatsuba(b,d)
ad_plus_bc=karatsuba(a+b, c+d)-ac-bd
return ac*(10**(2*half)) + (ad_plus_bc*(10**half)) + bd
x=1226
y=1345
xy=karatsuba(x,y)
print("Product of",x,"and",y,"is",xy)
Output: -