Daa Lab Da2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Design and Analysis of Algorithms Lab

COURSE CODE: BCSE204P


LAB ASSESSMENT-2
NAME: R HEMESH REG NO:22BCT0328
DIVIDE AND CONQUER:
1)MAXIMUM SUBARRAY:
Problem is to find maximum subarray sum of given 1-D array. Array
may contain negative and positive numbers which makes this a
difficult problem. Brute force will take O(N^2) time while a divide and
conquer approach will take O(N log N) time.

If all the array entries were positive, then the maximum-subarray


problem would present no challenge, since the entire array would give
the greatest sum.
ALGORITHM:
1. Divide the given array in two halves
2. Return the maximum of following three
➢ Recursively calculate Maximum subarray sum in left half .
➢ Recursively calculate Maximum subarray sum in right half .
➢ Recursively calculate Maximum subarray sum such that the
subarray crosses the midpoint
• Find the maximum sum starting from mid-point and
ending at some point on the left of mid.
• Find the maximum sum starting from mid+1 and ending
with some point on right of mid+1.
• Finally, combine the two and return.
CODE:
def maxCrossSum(arr, l, m, h):

s = 0
left_sum = -10000

for i in range(m, l-1, -1):


s = s + arr[i]
if (s > left_sum):
left_sum = s

s = 0
right_sum = -1000
for i in range(m, h + 1):
s = s + arr[i]

if (s > right_sum):
right_sum = s
return max(right_sum+left_sum-arr[m],left_sum,right_sum)

def maxSubArraySum(arr, l, h):

if (l > h):
return -10000

if (l == h):
return arr[l]

m = (l + h) // 2

return max(maxSubArraySum(arr, l, m-1),


maxSubArraySum(arr, m+1, h),
maxCrossSum(arr, l, m, h))

arr = [2, 1, -3, 4, -1, 2 , 1, -5 , 4]


n = len(arr)
max_sum = maxSubArraySum(arr, 0, n-1)
print("Maximum contiguous sum is ", max_sum)
OUTPUT:
ANOTHER EXAMPLE:

arr = [2, -5,6,-2,-3,1,5,-6]


2)KARATSUBA FASTER INTEGER MULTIPLICATION
ALGORITHM:

The Karatsuba algorithm is used by the system to perform fast


multiplication on two n-digit numbers, i.e. the system compiler takes
lesser time to compute the product than the time-taken by a normal
multiplication. The main idea of the Karatsuba Algorithm is to reduce
multiplication of multiple sub problems to multiplication of three sub
problems. Arithmetic operations like additions and subtractions are
performed for other computations.
ALGORITHM:
• Input: Two n-digit integers, x and y.
• If either x or y is less than 10, return the product of x and y.
• Determine the number of digits, n, in the largest input number.
Let n_2 be the half of n.
• Split the input numbers x and y each into two halves, a and b for
x and c and d for y, where a and c are the first n_2 digits of x and
y, and b and d are the last n_2 digits of x and y.
x = 10^(n/2)*a + b
y = 10^(n/2)*c + d

• Recursively compute c0 = karatsuba(b, d), c1 = karatsuba(a, c),


and c2 = karatsuba((a+b), (c+d)) - c0 - c1 using the Karatsuba
algorithm.
c0 = b * d
c1 = a * c
c2 = (a+b)*(c+d) – c0 -c1
• Compute the product as follows: c1 * 10^n + c2 * 10^n_2 + c0.
product = (c1*10^n)+(c2*10^(n/2))+c0
• Return the computed product.
• Output: The product of x and y.
CODE:
def karatsuba(x,y):
if x < 10 or y<10:
return x*y

n=max(len(str(x)),len(str(y)))
n_2=n//2

a=x// 10**n_2
b=x% 10**n_2
c=y// 10**n_2
d=y% 10**n_2

c0=karatsuba(b,d)
c1=karatsuba(a,c)
c2=karatsuba((a+b),(c+d))-c0-c1

return ((c1*(10**(2*n_2)))+(c2*(10**n_2))+c0)
x=1456
y=6425
product=karatsuba(x,y)
print("Product of given numbers "+str(x)+","+str(y)+"is :"+str(product))

OUTPUT:

If x=783932 and y=971 then x*y:


Another example:
BACK TRACKING:
3)N- QUEENS PROBLEM:
The N Queen is the problem of placing N chess queens on
an N×N chessboard so that no two queens attack each other. The idea
is to place queens one by one in different columns, starting from the
leftmost column. When we place a queen in a column, we check for
clashes with already placed queens. In the current column, if we find a
row for which there is no clash, we mark this row and column as part
of the solution. If we do not find such a row due to clashes, then we
backtrack and return false.
ALGORITHM:
• Define a function is_safe(board, row, col, n) to check if placing a
queen at position (row, col) on the board is safe.
o Check if there is a queen in the same column (col) in any of
the rows above (row).
o Check the upper diagonal on the left side to ensure there are
no queens.
o Check the upper diagonal on the right side to ensure there
are no queens.
• Define a recursive function solve_n_queens_util(board, row, n,
solutions) to find all solutions to the N-Queens problem.
o If row reaches n, we have found a solution. Append the
solution to the list of solutions.
o Try placing a queen in each column of the current row (row)
and recursively call solve_n_queens_util for the next row.
• Define the main function solve_n_queens(n) to initialize the board,
call solve_n_queens_util, and return the list of solutions.
• In the main program, call solve_n_queens(n) to get all solutions for
the given n and print them in the desired format.
CODE:
def is_safe(board, row, col, n):
# Check if there is a queen in the same column
for i in range(row):
if board[i][col] == 1:
return False

# Check upper diagonal on left side


for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False

# Check upper diagonal on right side


for i, j in zip(range(row, -1, -1), range(col, n)):
if board[i][j] == 1:
return False

return True

def solve_n_queens_util(board, row, n, solutions):


if row == n:
solution = []
for i in range(n):
for j in range(n):
if board[i][j] == 1:
solution.append((i, j))
solutions.append(solution)
return

for col in range(n):


if is_safe(board, row, col, n):
board[row][col] = 1
solve_n_queens_util(board, row + 1, n, solutions)
board[row][col] = 0

def solve_n_queens(n):
board = [[0 for _ in range(n)] for _ in range(n)]
solutions = []
solve_n_queens_util(board, 0, n, solutions)
return solutions

def print_solution(solution):
for row in solution:
line = ["0"] * len(solution)
line[row[1]] = "1"
print("[" + ", ".join(line) + "]")
print("\n")
print("enter the number of queens value (n): ")
n = int(input())
solutions = solve_n_queens(n)
for i, solution in enumerate(solutions, 1):
print(f"Solution {i}:")
print_solution(solution)
OUTPUT:
FULL SCREENSHOT OF SCREEN WITH OUTPUTS FOR INPUTS N=4,5:

You might also like