0% found this document useful (0 votes)
12 views16 pages

DAA_1_ASS_redesigned

The document outlines an assignment consisting of ten programming tasks related to algorithms and data structures. Each task includes a description, code implementation, expected output, and an analysis of time complexity. The tasks cover various topics such as prime number generation, GCD calculation, uniqueness in arrays, matrix multiplication, and solving optimization problems like the Traveling Salesman Problem and job assignment.

Uploaded by

23csec61.sehwag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views16 pages

DAA_1_ASS_redesigned

The document outlines an assignment consisting of ten programming tasks related to algorithms and data structures. Each task includes a description, code implementation, expected output, and an analysis of time complexity. The tasks cover various topics such as prime number generation, GCD calculation, uniqueness in arrays, matrix multiplication, and solving optimization problems like the Traveling Salesman Problem and job assignment.

Uploaded by

23csec61.sehwag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

ASSIGNMENT - 1

NAME: DEEPAN.S COURSE CODE:21CS207

ROLL NO:23CSEC39 COURSE TITLE: Design Analysis &


m Algorithm

CLASS & SEC:II-CSE C BRANCH: CSE

1. Develop a program to print all the prime numbers in a given range using sieve of
Eratosthenes algorithm and find its time complexity.

CODE:
def sieve_of_eratosthenes(n):

primes = [True] * (n + 1)

primes[0] = primes[1] = False

for i in range(2, int(n**0.5) + 1):

if primes[i]:

for j in range(i * i, n + 1, i):

primes[j] = False

return [i for i in range(n + 1) if primes[i]:

if __name__ == "__main__":

n = int(input("Enter the upper limit: "))

primes = sieve_of_eratosthenes(n)

print(f"Prime numbers up to {n}: {primes}")

print("Time Complexity: O(n log log n)")

OUTPUT:

2. Develop a program to find the GCD of two numbers using Euclid’s algorithm.

CODE:

def gcd(a, b):

DEEPAN S 23CSEC39
while b:
a, b = b, a % b
return a
if __name__ == "__main__":
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(f"GCD of {a} and {b} is {gcd(a, b)}")
print("Time Complexity for GCD: O(log min(a, b))")

OUTPUT:

3. Implement a program to determine if all elements in a given array are unique. The
program should check if there are no duplicate elements in the array.

CODE:

def all_unique(arr):
return len(arr) == len(set(arr))
if __name__ == "__main__":
arr = list(map(int, input("Enter elements separated by space: ").split()))
print("All elements are unique:" if all_unique(arr) else "Duplicates found")

OUTPUT:

4. Implement a program to find maximum element in an array. Provide the program,


test cases, and an analysis of its time complexity.

CODE:

DEEPAN S 23CSEC39
def find_max(arr):
if not arr:
return None
return max(arr)

if __name__ == "__main__":
arr = list(map(int, input("Enter elements separated by space: ").split()))
max_element = find_max(arr)
print(f"Maximum element: {max_element}")
# Test cases
test_cases = [
([3, 1, 4, 1, 5, 9, 2, 6], 9),
([10, 20, 30, 40, 50], 50),
([-5, -1, -10, -3], -1),
([7], 7),
([], None)
]
for i, (test, expected) in enumerate(test_cases, 1):
result = find_max(test)
print(f"Test Case {i}: {'Pass' if result == expected else 'Fail'}")
# Time complexity analysis

print("Time Complexity: O(n)")

OUTPUT:

DEEPAN S 23CSEC39
5. Implement a program to perform matrix multiplication. The program should check
whether matrix multiplication is possible and display the output accordingly.

CODE:

def matrix_multiply(A, B):


if len(A[0]) != len(B):
return None
result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in
range(len(A))]
return result

if __name__ == "__main__":
import numpy as np

rows_A, cols_A = map(int, input("Enter dimensions of first matrix (rows cols): ").split())
A = [list(map(int, input().split())) for _ in range(rows_A)]

rows_B, cols_B = map(int, input("Enter dimensions of second matrix (rows cols):


").split())
B = [list(map(int, input().split())) for _ in range(rows_B)]

if cols_A != rows_B:
print("Matrix multiplication not possible")

DEEPAN S 23CSEC39
else:
result = matrix_multiply(A, B)
print("Resultant Matrix:")
for row in result:
print(" ".join(map(str, row)))

print("Time Complexity: O(n^3) for general case, O(n^2.807) with Strassen's algorithm")

OUTPUT:

6. Write a program to find all occurrences of a given substring within a larger string
using a brute force approach. The program should print the starting index of each
occurrence. Provide the program, test cases, and an analysis of its time
complexity.

CODE:

def find_substring_occurrences(text, pattern):


occurrences = []
for i in range(len(text) - len(pattern) + 1):
if text[i:i+len(pattern)] == pattern:
occurrences.append(i)
return occurrences

if __name__ == "__main__":

DEEPAN S 23CSEC39
text = input("Enter the main text: ")
pattern = input("Enter the substring to find: ")
indices = find_substring_occurrences(text, pattern)
if indices:
print("Substring found at indices:", indices)
else:
print("Substring not found.")
# Test cases
test_cases = [
("abracadabra", "abra", [0, 7]),
("hello world, hello universe", "hello", [0, 13]),
("aaaaaa", "aa", [0, 1, 2, 3, 4]),
("abcdef", "xyz", []),
("abcabcabc", "abc", [0, 3, 6])
]
for i, (txt, pat, expected) in enumerate(test_cases, 1):
result = find_substring_occurrences(txt, pat)
print(f"Test Case {i}: {'Pass' if result == expected else 'Fail'}")

print("Time Complexity: O((n-m+1) * m), where n is the length of text and m is the length
of the pattern.")

OUTPUT:

7. Implement Knapsack problem using a brute force approach. The program should

DEEPAN S 23CSEC39
find the maximum value that can be obtained by selecting items with given
weights and values to fit in a knapsack of a given capacity. Provide the program,
test cases, and an analysis of its time complexity.

CODE:

def knapsack_brute_force(weights, values, capacity, n):


if n == 0 or capacity == 0:
return 0
if weights[n-1] > capacity:
return knapsack_brute_force(weights, values, capacity, n-1)
else:
return max(
values[n-1] + knapsack_brute_force(weights, values, capacity - weights[n-1], n-1),
knapsack_brute_force(weights, values, capacity, n-1)
)

if __name__ == "__main__":
n = int(input("Enter number of items: "))
weights = list(map(int, input("Enter weights separated by space: ").split()))
values = list(map(int, input("Enter values separated by space: ").split()))
capacity = int(input("Enter knapsack capacity: "))

max_value = knapsack_brute_force(weights, values, capacity, n)


print(f"Maximum value possible: {max_value}")

# Test cases
test_cases = [
([2, 3, 4, 5], [3, 4, 5, 6], 5, 10),
([1, 2, 3], [10, 15, 40], 5, 55),
([5, 10, 20], [50, 60, 140], 15, 110),

DEEPAN S 23CSEC39
([1, 1, 1], [10, 20, 30], 2, 50),
([4, 2, 3], [10, 4, 7], 6, 14)
]

for i, (w, v, cap, expected) in enumerate(test_cases, 1):


result = knapsack_brute_force(w, v, cap, len(w))
print(f"Test Case {i}: {'Pass' if result == expected else 'Fail'}")

print("Time Complexity: O(2^n), where n is the number of items.")

OUTPUT:

8. Write a program to crack a simple password by trying all possible combinations of


alphanumeric characters up to a given length using a brute force approach.
Provide the program, test cases, and an analysis of its time complexity.

CODE:

import itertools
import string

def brute_force_crack(target, max_length):


chars = string.ascii_letters + string.digits

DEEPAN S 23CSEC39
for length in range(1, max_length + 1):
for attempt in itertools.product(chars, repeat=length):
if "".join(attempt) == target:
return "".join(attempt)
return None

if __name__ == "__main__":
target_password = input("Enter the password to crack: ")
max_length = int(input("Enter the maximum length to try: "))

cracked_password = brute_force_crack(target_password, max_length)


if cracked_password:
print(f"Password cracked: {cracked_password}")
else:
print("Password not found within given length limit.")

# Test cases
test_cases = [
("abc", 3, "abc"),
("A1B", 3, "A1B"),
("xyz9", 4, "xyz9"),
("1234", 3, None),
("Zz9", 5, "Zz9")
]

for i, (password, length, expected) in enumerate(test_cases, 1):


result = brute_force_crack(password, length)
print(f"Test Case {i}: {'Pass' if result == expected else 'Fail'}")

DEEPAN S 23CSEC39
print("Time Complexity: O(c^n), where c is the number of characters to try and n is the
password length.")

OUTPUT:

9. Implement Traveling Salesman Problem using brute force algorithm. The program
should take a list of cities and their coordinates as input and output the shortest
route and its total distance. Provide the program, test cases, and an analysis of
its time complexity.

CODE:

import itertools
import math

def distance(city1, city2):


return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)

def traveling_salesman_brute_force(cities):
min_path = None
min_distance = float('inf')
for perm in itertools.permutations(cities[1:]):
path = [cities[0]] + list(perm) + [cities[0]]
total_distance = sum(distance(path[i], path[i+1]) for i in range(len(path) - 1))
if total_distance < min_distance:
min_distance = total_distance

DEEPAN S 23CSEC39
min_path = path
return min_path, min_distance
if __name__ == "__main__":
n = int(input("Enter number of cities: "))
cities = []
for i in range(n):
x, y = map(int, input(f"Enter coordinates of city {i+1} (x y): ").split())
cities.append((x, y))
path, distance = traveling_salesman_brute_force(cities)
print("Shortest path:", path)
print("Total distance:", distance)
# Test cases
test_cases = [
([(0, 0), (2, 2), (2, 0), (0, 2)], 8.0),
([(1, 1), (4, 4), (4, 1), (1, 4)], 12.0),
([(0, 0), (3, 4), (6, 0)], 12.0),
([(0, 0), (1, 1), (2, 2), (3, 3)], 6.83)
]
for i, (cities, expected) in enumerate(test_cases, 1):
_, result = traveling_salesman_brute_force(cities)
print(f"Test Case {i}: {'Pass' if round(result, 2) == expected else 'Fail'}")

print("Time Complexity: O(n!), where n is the number of cities.")

OUTPUT:

DEEPAN S 23CSEC39
10. Given a cost matrix, where the element at cost[i][j] represents the cost of
assigning the i-th job to the j-th worker, develop a program to find the assignment
of jobs to workers such that the total cost is minimized using a brute force
approach.

CODE:

import itertools
def calculate_cost(cost_matrix, assignment):
return sum(cost_matrix[i][assignment[i]] for i in range(len(assignment))
def job_assignment_brute_force(cost_matrix):
n = len(cost_matrix)
workers = range(n)
min_cost = float('inf')
best_assignment = None
for perm in itertools.permutations(workers):
current_cost = calculate_cost(cost_matrix, perm)
if current_cost < min_cost:
min_cost = current_cost
best_assignment = perm
return best_assignment, min_cost
if __name__ == "__main__":
n = int(input("Enter number of jobs/workers: "))
cost_matrix = []
for i in range(n):
row = list(map(int, input(f"Enter costs for job {i+1} (space-separated): ").split()))
cost_matrix.append(row)
assignment, min_cost = job_assignment_brute_force(cost_matrix)
print("Optimal assignment:", assignment)
print("Minimum cost:", min_cost)
# Test cases

DEEPAN S 23CSEC39
test_cases = [
([[9, 2, 7], [6, 4, 3], [5, 8, 1]], 7),
([[4, 1], [2, 5]], 3),
([[10, 3, 8, 7], [5, 2, 6, 9], [1, 4, 7, 8], [9, 6, 3, 5]], 13)
]
for i, (matrix, expected) in enumerate(test_cases, 1):
_, result = job_assignment_brute_force(matrix)
print(f"Test Case {i}: {'Pass' if result == expected else 'Fail'}")

print("Time Complexity: O(n!), where n is the number of jobs/workers.")

OUTPUT:

RUBRICS:

DEEPAN S 23CSEC39
DEEPAN S 23CSEC39
DEEPAN S 23CSEC39
DEEPAN S 23CSEC39

You might also like