Nothing Special   »   [go: up one dir, main page]

Daa Lab Sample

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

21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB WORKBOOK

21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

1
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LABORATORY WORKBOOK

STUDENTNAME
REG.NO
YEAR
SEMESTER
SECTION
FACULTY

3
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Table of Contents

ORGANIZATION OF THE STUDENTLABWORKBOOK ..................................5


LAB 01 ......................................................................................................8
LAB 02 ....................................................................................................16
LAB 03 ....................................................................................................23
LAB 04 ...................................................................................................30
LAB 05 ....................................................................................................37
LAB 06 ....................................................................................................42
LAB 07 ....................................................................................................47
LAB 08 ....................................................................................................52
LAB 09 ....................................................................................................59
LAB 10 ....................................................................................................65
LAB 11 ....................................................................................................70
LAB 12 ....................................................................................................75

4
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Organization of the STUDENT LAB WORKBOOK

The laboratory framework includes a creative element but shifts the time-intensive
aspects outside of the Two-Hour closed laboratory period. Within this structure, each
laboratory includes three parts: Pre-lab, In-lab, and Post-lab.

a. Pre-Lab

The Pre-lab exercise is a homework assignment that links the lecture with the laboratory
period - typically takes 2 hours to complete. The goal is to synthesize the information
they learn in lecture with material from their textbook to produce a working piece of
software. Pre-lab Students attending a two-hour closed laboratory are expected to make
a good-faith effort to complete the Pre-lab exercise before coming to the lab. Their work
need not be perfect, but their effort must be real (roughly 80 percent correct).
b. In-Lab

The In-lab section takes place during the actual laboratory period. The First hour of the
laboratory period can be used to resolve any problems the students might have
experienced in completing the Pre-lab exercises. The intent is to give constructive
feedback so that students leave the lab with working Pre-lab software - a significant
accomplishment on their part. During the second hour, students complete the In-lab
exercise to reinforce the concepts learned in the Pre-lab. Students leave the lab having
received feedback on their Pre-lab and In-lab work.
c. Post-Lab

The last phase of each laboratory is a homework assignment that is done following the
laboratory period. In the Post-lab, students analyze the efficiency or utility of a given
system call. Each Post-lab exercise should take roughly 120 minutes to complete.

5
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2022-23 EVEN SEMESTER LAB CONTINUOUS EVALUATION

In-Lab
S. Pre-Lab Post- Viva Voce Total Faculty
No. Date Experiment Name (5M) Lab (5M) (50M) Signature
Logic Execution Result Analysis
(5M)
(10M) (10M) (10M) (5M)
1.

2.

3.

4.

5.

6.

7.

8.

6
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2022-23 EVEN SEMESTER LAB CONTINUOUS EVALUATION

In-Lab
S. Pre-Lab Post- Viva Voce Total Faculty
No. Date Experiment Name (5M) Lab (5M) (50M) Signature
Logic Execution Result Analysis
(5M)
(10M) (10M) (10M) (5M)
9.

10.

11.

12.

7
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 01: TIME COMPLEXITY AND SPACE COMPLEXITY


Date of the Session: / / Time of the Session: to

Pre-Lab:

1) During lockdown Mothi gets bored by his daily routine while scrolling youtube he found an
algorithm that looks different Mothi is very crazy about algorithms, but he cannot solve algorithms
of multiple loops so that he structed and need your help to find the time complexity of that
algorithm

Algorithm that was found on internet:


Algoritm KLU(int n)
{
int count=0;
for(int i=0;i<n;i=i*2)
{
for(int j=n;j>0;j=j/3)
{
for(int k=0;k<n;k++)
{
Count++;
}
}
}
}

8
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Klaus Michaelson is interviewer, so he prepared a bunch of questions for the students. He focused on
algorithms. Among all the questions the easiest question is what is the time complexity of the
following C function is so can answer to this?
int recursive(int n)
{
if(n==1)
return (1);
else
return(recursive (n-1) + recursive (n-1));}

9
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

3) Mothi has 2 algorithms and he also know their time functions. Now he wants to analyze which one is
greater function? But Mothi do not know how to compare two-time functions. Your task is to analyze
the given two-time functions and judge which one is greater and justify with your solution

a) T1(n) = (log(n^2)*log(n)) T2(n) = log(n*(logn)^10)

b) T1(n) = 3*(n)^(sqrt(n)) T2(n) = (2)^(sqrt(n)*logn) (consider logn with base 2)

10
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

In-Lab:

1) Caroline Forbes is an intelligent girl, every time she wins in any contest or programme, and solves
complex problems so I want to give her a challenge problem that is. Sort an array of strings according
to string lengths. If you are smarter than her, try to solve the problem faster than her?
Input
You are beautiful looking
Output
You are looking beautiful

11
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Kiran Kumar is the Assistant Professor of Computer science department so he just ask to interact with
the students and helps the students to solve the complex problems in an easier way so, the problem
given by the sir is sort an array according to count of set bits?

Example:
Input: arr[] = {1, 2, 3, 4, 5, 6};
Output: 3 5 6 1 2 4
Explanation:
3 - 0011
5 - 0101
6 - 0110
1 - 0001
2 - 0010
4 - 0100
hence the non-increasing sorted order is
{3, 5, 6}, {1, 2, 4}

12
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

3) During the final skill exam teacher was given a problem and asked everyone to write the algorithm to
it, and advised that try to implement a different approach from others.
Question: Write an algorithm to calculate sum of first 'n' natural numbers
Mothi, one of the student in the class thinking that his friends will write an efficient algorithm to that
question. So, he wants to write a worst approach to make that algorithm as unique.

Algorithm:
Algorithm SumOfNNaturalNums(int n)
{
int count=0;
for( i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
count++;
}
}
return count;
}

13
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:
1) Given an array arr[] of N strings, the task is to sort these strings according to the number of upper-case
letters in them try to use zip function to get the format.

Input arr[] = {poiNtEr, aRRAy, cOde, foR}


Output: [('cOde', 1), ('foR', 1), ('poiNtEr', 2), ('aRRAy', 3)]

“aRRAy” R, R, A->3 Upper Case Letters


“poiNtEr” N, E->2 Upper Case Letters
“cOde” O->2 Upper Case Letters
“foR” R->3 Upper Case Letters

14
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) In KLU streets we have lots of electrical poles.


Note: all poles are sorted with respective to their heights.

Professor Hari Vege given the H = height of one pole to Mothi then asked him to print the position of
that pole, here we consider index as a position. Mothi is particularly good at algorithms, so he written
an algorithm to find that position. But he is extremely poor at finding time complexity. Your task is to
help your friend Mothi to analyze the time complexity of the given problem.

Int BinarySearch (int a, int low, int high, int tar)


{
int mid;
if (low > high) return 0;
mid = floor((low + high)/2)
if (a[mid] == tar)
return mid;
else if (tar < a[mid])
return BinarySearch (a, low, mid-1, tar)
else
return BinarySearch (a, mid+1, high, tar)
}

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

15
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 02: STRING MATCHING


Date of the Session: / / Time of the Session: to

Pre-Lab:

1) Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search (char pat [], char
txt[]) that prints all occurrences of pat[] in txt[] using naïve string algorithm?(assume that n > m)
Input
txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output
Pattern found at index 10
Input
txt[] = "AABAACAADAABAABA"
pat[] = "AABA"
Output
Pattern found at index 0
Pattern found at index 9

16
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Discuss the Rabin Karp algorithm for string matching and explain time complexity of the algorithm?

17
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

3) Stefan is a guy who is suffering with OCD. He always like to align things in an order. He got a lot of
strings for his birthday party as gifts. He like to sort the strings in a unique way. He wants his strings
to be sorted based on the count of characters that are present in the string.
Input
aaabbc
cbbaaa
Output
aabbcc
aabbcc

If in case when there are two characters is same, then the lexicographically smaller one will be printed
first

Input:
aabbccdd
aabcc
Output:
aabbccdd
baacc

18
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

In-Lab:
1) Naive method and KMP are two string comparison methods. Write a program for Naïve method and
KMP to check whether a pattern is present in a string or not. Using clock function find execution time
for both and compare the time complexities of both the programs (for larger inputs) and discuss which
one is more efficient and why?

Sample program with function which calculate execution time:

#include<stdio.h>
#include<time.h>
void fun()
{
//some statements here
}
int main()
{
//calculate time taken by fun()
clock_t t;
t=clock();
fun();
t=clock()-t;
double time_taken=((double)t)/CLOCK_PER_SEC; //in seconds
printf(“fun() took %f seconds to execute \n”,time_taken);
return 0;
}

19
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Andrea is working in a photo studio where his boss has given him a task to arrange the photos of
family members. He is French and he do not know English somehow, he managed to send the list of
names to you (his friend). Help Andrea to sort the photos.
(Note: implement the odd even merge algorithm)
Input
5
Neil Katherine Harry Stefan Dennis
Output
Dennis Harry Katherine Neil Stefan

20
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:
1) Given a pattern of length- 5 window, find the valid match in the given text by step-by-step process
using Robin-Karp algorithm
Pattern: 2 1 9 3 6
Modulus: 21
Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Text: 9 2 7 2 1 8 3 0 5 7 1 2 1 2 1 9 3 6 2 3 9 7

21
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) James is sharing his information with his friend secretly in a chat. But he thinks that message
should not understandable to anyone only for him and his friend. So he sent the message in the
following format.
Input
a1b2c3d4e
Output
abbdcfdhe
Explanation:
The digits are replaced as follows:
- s[1] -> shift('a',1) = 'b'
- s[3] -> shift('b',2) = 'd'
- s[5] -> shift('c',3) = 'f'
- s[7] -> shift('d',4) = 'h'

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

22
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 03: SORTING


Date of the Session: / / Time of the Session: to
Pre-Lab:

1) Write a Divide and Conquer algorithm to find the minimum distance between the pair of the points
given in an array. Find the time complexity of the algorithm.

P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}

23
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Write a divide and conquer algorithm for finding the maximum and minimum in the sequence of
numbers. Find the time complexity.

24
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

3) Trace out the output of the following using Merge sort.10, 49, 32, 67, 45, 4, 7, 2, 1, 51, 78, 34, 89,
87, 36, 29, 3, 9, 11.

25
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

In-Lab:
1) Harry’s Aunt and family treat him badly and make him work all the time. Dudley, his cousin got
homework from school and he as usual handed it over to Harry but Harry has a lot of work and his
own homework to do.
The homework is to solve the problems which are numbered in numerical he tries to solve random
question after solving random questions he did not put those questions in order Dudley will return
in a time of n*logn Harry has to arrange them as soon as possible. Help Harry to solve this
problem so that he can go on and do his own homework.
Example
Input
9
15,5,24,8,1,3,16,10,20
Output
1, 3, 5, 8, 10, 15, 16, 20, 24

26
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) A group of 9 friends are playing a game, rules of the game are as follows: Each member will be
assigned with a number and the sequence goes like e.g.: 7,6,10,5,9,2,1,15,7.
Now they will be sorted in ascending order in such a way that tallest one will be sorted first. Now
your task is to find the order of indices based on initial position of the given sequence and print the
order of indices at the end of the iteration.

27
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:

1) Suppose a merge sort algorithm, for input size 64, takes 30 secs in the worst case. What is the
maximum input size that can be calculated in 6 minutes (approximately)?

28
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Chris and Scarlett were playing a block sorting game where Scarlett challenged Chris that he has to
sort the blocks which arranged in random order. And Scarlett puts a restriction that he should not use
reference of first, median and last blocks to sort, and after sorting one block with reference to other
block, for next iteration he must choose another block as the reference not the same block (random
pivot).
Now, Chris wants help from you to sort the blocks. He wanted to sort them in a least time. Help him
with the least time complexity sorting algorithm.
Input format
First line of input contains the number of test cases.
Next t lines of input contain
The number of blocks provided by Scarlett.
The array of blocks.

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

29
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 04: STRASSEN’S MULTIPLICATION AND CONVEX


HULL

Date of the Session: _ / / Time of the Session: _ to


Pre-Lab:

1) Trace the output of the following matrix multiplication using Strassen’s Multiplication Method

A, B and C are the Matrices of Size NxN


a, b, c and d are the sub-Matrices of A of size N/2xN/2
e, f, g and h are the sub-Matrices of B of size N/2xN/2

30
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) China had recently banned cryptocurrency. Due to this cryptocurrency cost has fallen drastically. Mr.
Lee has lost a lot so he could not afford a stock advisor. He came to you (his friend) for help. He has
the prices of stock on i’th day. Help him to find the maximum profit he can achieve. You may
complete as many transactions as you like.
Input
7
[1,2,3,4,5,6,7]
Output
6
Explanation:
Buy the stock on 1st day at cost 1Rupee and sell the stock on 7th day at cost 7 Rupee and get profit of 6
rupees.

31
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

In-Lab:

1) You are given 2 matrices of any size N*N. Write a program to find the product of the two matrixes
(use Strassen’s Matrix Multiplication).

32
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Mr. Lee is working in a construction where they had to fencing around trees in a field. The owner
has asked a rough estimate to do fencing in that field such all the trees lie inside that region.
Consider yourself as a cost estimator who works under Mr. Lee. You are given location of all the
trees, and you need to find the points that include this fencing. You need to output the trees that
are included in the fencing.
Input:
points = [[1,1], [2,2], [2,0], [2,4], [3,3], [4,2]]
Output:
[[1,1], [2,0], [3,3], [2,4], [4,2]]

33
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

3) In a school there was conducted a contest among two groups. As part of the contest each group must
re-arrange the cards that had given to the members in ascending order. Consider yourself as a part of
the team and find the best viable way to win that round.
Input
3
3
[[2,5,6], [4,8,7], [9,3,1]]
Output
[1,2,3,4,5,6,7,8,9]

34
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:

1) Mr. Hari Kumar owns a fruit market. In the market there are many sellers who are selling many kinds
of fruits. More than one fruits seller can sell same kind of fruit. Mr. Hari Kumar wants to arrange their
information in the sorted order based on their names of the sellers and id of the fruits. You must
arrange the same type of fruits in the same order as original order.
0-mangoes 1-apples
[Hint: Use counting sort algorithm]
Input
4
[[0, c], [1, b], [0, a], [1, d]]
Output
[[0, a], [0, c], [1, b], [1, d]]

35
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Given a set of points in the plane, apply convex hull algorithm to the given points and explain it step
by step process.

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:


36
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 05: GREEDY METHOD


Date of the Session: / / Time of the Session: to

Pre-Lab:

1) Explain why 0-1 Knapsack problems cannot be solved using greedy method unlike fractional
knapsack.

2) Categorize the Following as single source or multiple source shortest path algorithms.

Floyd-Warshall algorithm –
Dijkstra’s algorithm –
Bellman-Ford algorithm –

3) List down various shortest path greedy algorithms.

37
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS
In-Lab:
1) Given an array of size n that has the following specifications:
a. Each element in the array contains either a police officer or a thief.
b. Each police officer can catch only one thief.
c. A police officer cannot catch a thief who is more than K units away from the police officer.

We need to find the maximum number of thieves that can be caught.


Input
arr [] = {'P', 'T', 'T', 'P', 'T'},
k = 1.
Output
2
Here maximum 2 thieves can be caught; first police officer catches first thief and second police
officer can catch either second or third thief.

38
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n
vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines,
which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
Input
height = [1,8,6,2,5,4,8,3,7]
Output
49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the
max area of water (blue section) the container

39
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:
1) Given an array of jobs where every job has a deadline and associated profit if the job is finished
before the deadline. It is also given that every job takes a single unit of time, so the minimum possible
deadline for any job is 1. How to maximize total profit if only one job can be scheduled at a time.
Input
4
Job ID Deadline Profit
a 4 20
b 1 10
c 1 40
d 1 30
Output
60
profit sequence of jobs is c, a

40
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) There are N Mice and N holes are placed in a straight line. Each hole can accommodate only 1
mouse. A mouse can stay at his position, move one step right from x to x + 1, or move one step left
from x to x − 1. Any of these moves consumes 1 minute. Assign mice to holes so that the time when
the last mouse gets inside a hole is minimized.

Example: positions of mice are: 4 -4 2


Positions of holes are: 4 0 5
Input
A: list of positions of mice
B: list of positions of holes
Output
single integer value

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

41
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 06: JOB SEQUENCING, HUFFMAN CODING


Date of the Session: / / Time of the Session: to
Pre-Lab:

1) Our TASC has the information that a scientist has gone crazy and was planning a gas leakage in
Delhi. We do not know the exact location where he was planning to do this attack. When Srikanth
Tiwari tried to catch him, The Scientist tried to kill himself and has gone into coma in this process.
Now no one knows the location of the attack except he has kept all the information in a file in his
private server, but it is encoded using Huffman coding. So, help NIA decode the information. Given
the root of the graph and the encoded information write a function to decode it. The function will
have input parameters of root node and encoded string.
Input
Encoded String-1001011
Output
ABACA

42
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

In-Lab:

1) You are a Human resource manager working in a Startup. You are tasked with to utilize the best of the
working professionals to get the maximum profit for different jobs of a Project.
An array of jobs is given where every job has a deadline and associated profit if the job is finished
before the deadline. It is also given that every job takes single unit of time, so the minimum possible
deadline for any job is 1.How to maximize total profit if only one job can be scheduled at a time.
Write a code for the following problem.
Input
7
abcdefg
3442312
35 30 25 20 15 12 5
Output
110
dcab

43
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Surya is a student at KL University, He is currently standing in the C-Block. He has 8 friends who are
situated at different Blocks (Places) inside the university and he wishes to talk to each of them in
person. The distances are represented on the undirected graph which is provided below. He wishes to
take the shortest distance for each place from his location. Help him in meeting every one of his
friends by developing a program that can determine the shortest distance between the C-Block and
every other place on the graph. Remember that the path is not required.

Hint: Use Dijkstra’s algorithm to calculate the distances between the C-Block and every other place
Output for the same is provided along with the question.

Output:
Vertex Distance from Source
C Block 0
FED Block 4
S Block 12
Main Canteen 19
Entrance 21
Xerox 11
R&D Block 9
Mech Block 8
Library 14

44
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:
1) Mr. Tripathiis a network cable operator. He now shifted to a new city where he needs to work on
designing the cable lines to each street/colony. Given the graph and each node represents a street,
help him to design an optimal cable line using prim's algorithm. Write a program to solve this.

45
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS
1. Mr.Tripathi done with designing the cable lines but now there comes a new task, that is working on
street lines. Help him again to find weight of the graph using Kruskal algorithm. Write a program to
solve this.

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

46
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 07: DYNAMIC PROGRAMMING


Date of the Session: / / Time of the Session: to

Pre-Lab:
1) A student named Satish is eagerly waiting to attend tomorrow’s class. As he searched the concepts of
tomorrow’s lecture in the course handout and started solving the problems, in the middle he was
stroked in the concept of strings because he was poor in this concept so help him so solve the
problem, given two strings str1 and str2 and below operations that can performed on str1. Find
minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.
1. Insert
2.Remove
3.Replace
Input
str1 = "cat", str2 = "cut"
Output
1
We can convert str1 into str2 by replacing 'a' with 'u'.
Input
str1 = "sunday", str2 = "saturday"
Output
3

47
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Given N numbers n1,n2,…nN and Q queries q1,q2,…qQ. Your task is to print Q (Q< j <numbers)
f1,f2,…fQ, corresponding to query qj1 max(n1=fj ,n2 ,...nq) using dynamic programming.
Input
53
54869
235
Output
589

48
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

In-Lab:
1) Bhanu is a student at KL University who likes playing with strings, after reading a question from their
lab workbook for the ADA Course she found what is meant by a subsequence.
(A subsequence is a sequence that can be derived from another sequence by deleting some or no
elements without changing the order of the remaining elements)
So, she created 2 strings out of which one she considered as a master string and the other one as a
slave string. She challenged her friend Teju to find out whether the slave string is a subsequence of the
master string or not, As Teju is undergoing her CRT classes she decided to code the logic for this
question. Help her in building the logic and write a code using Dynamic programming concept.

49
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Raju has very less Marks in Dynamic programming test conducted by his teacher. So, the teacher had
given a problem about optimal Binary Search Tree which should be solved using Dynamic
Programming by the next class. Since, he is very weak in Dynamic programming you must help him
to solve the problem. The problem can be described as follows:
An unsorted data of keys and their frequencies are given to you and some queries where each query
contains two integers which describe the range of the indices (index range) for which you must print
the root of that Optimal Binary Search Tree.
Input
4
12 10 20 21
8 34 50 1
2
03
01
Output
Cost of Optimal BST is 144
20
1

50
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:

1) Bhanu and Teju are playing dice game where there are N dice with M faces and the dice are numbered
from 1 to M. A person wins the game if the sum of the faces of dice adds up to a value X. you are
playing on Bhanu’s team, and It is Teju’s turn now.
You are supposed to find number of ways your opponent can win the game where N, M and X are
provided as input. Use Dynamic programming to solve the problem.
Using DP (Dynamic programming) to find the number of ways to get sum X.
Input
M=2
N=2
X=3
Output
2

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

MarksSecured: outof
Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

51
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 08:


Date of the Session: / / Time of the Session: to
Pre-Lab:

1) Your father brought you a ticket to world tour. You have a choice to go to three places, your father
knows the places you wanted to travel so he made a graph with the measuring distances from home.
Now you start from your place (1: Source) to other places as shown in the graph below apply TSP to
find shortest path to visit all places and return to home. (Ex: 2: London, 3: Paris, 4: Singapore)

52
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) You are given a map(graph) with the distances between the places. Here you will consider the 1st
node as the starting point and ending point, Since the route is cyclic you can take any node as starting
point and ending point. Find the minimum cost route and remember the Hamiltonian cycle.

53
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

3) Your friend works in a comparable way to a Travelling salesperson ― he always travels to new cities
to sell his delicious dishes.

Today, your friend is planning to visit N cities (numbered 1 through N). There is a direct way to travel
between each pair of cities. Each city has a specific temperature; let us denote the temperature in the i-
th city by Ci. Your friend has a fixed temperature tolerance D with the following meaning: for each
pair of cities an and b, he may travel from city a directly to city b only if |Ca−Cb|≤D, otherwise he
would catch a heavy flu because of the sudden change in temperature.
Your friend starts from city 1. Is he able to visit all N cities in such a way that each city is visited
exactly once?
Notes:
1. Your friend is not able to travel through a city without visiting it.
2. City 1 is visited at the beginning.
It is not necessary to be able to travel directly to city 1 from the last city Your friend’s visits.
Input
2
53
32145
54
10 1 3 2 9
Output
Yes
No

54
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

In-Lab:

1) Emma has a graph which represents a flow network where every edge has a capacity. Also given two
vertices source s and sink t in the graph, fin the maximum possible flow from s to t with following
constraints:
a. Flow on an edge does not exceed the given capacity of the edge.
b. Incoming flow is equal to outgoing flow for every vertex except s and t.

Find the Maximum flow using the graph and by implementing the code.

55
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) For the above given graph Emma wants an s-t to cut that requires the source s and the sink t to be in
different subsets, and it consists of edges going from the source’s side to the sink’s side. So, she
wants you to find the minimum capacity s-t cut of the given network. Expected output is all the edges
of minimum cut.

56
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:

1) Hogwarts has yet again declared The Triwizard tournament. Harry must pass this round to get to the
next one. Each participant will be given a graph with vertices as shown below. Each vertex is a
dungeon, and a golden egg is placed in the root dungeon i.e., the root vertex. Help harry find the
dungeon with the golden egg using traversing or searching tree or graph data structure. (P.S: To pass
this round Harry must write a code).

57
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) KL University is starting next week. There are S subjects in total, and you need to choose K of them
to attend each day, you required number of credits to pass the semester. There are N+1 buildings.
Your hostel is in building number 0. Subject j is taught in building Bj. After each subject, you have a
break, during which you go back to your hostel. There are M bidirectional paths of length 1 which
connects building b1 to building b2. Find the minimum total distance you need to travel each day if
you choose your subjects correctly.
Input
2322
01
12
20
12
Output
4

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:


58
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 09: BACK TRACKING


Date of the Session: / / Time of the Session: to

Pre-Lab:
1) What is Back Tracking methodology and when can we use Back Tracking, explain with an example?

59
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS
2) Mr. Anumula went to the Ice-Cream Parlor. He will be with certain amount of money to buy ice-
creams. When he goes to the counter for ordering the Ice-cream, there will be displayed with the
items and its cost, respectively. He will be checking which items he can buy according to the money.
Print "YES" if he can buy the Ice-Creams without leaving one rupee also otherwise print "NO".
Input
costs= [100, 70, 50, 180, 120, 200, 150]
Total Money=300
Output
YES

60
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS
In-Lab:

1) Mani is poor at playing chess, he was asked to arrange “N” Queens on the chess board in such a way
that no two queens are allowed to kill each other. Since he is poor at chess you were asked to arrange
them on behalf of him. (You must use Backtracking Approach)

61
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Given an undirected graph and N colors, the problem is to find if it is possible to color the graph with
at most N colors, which means assigning colors to the vertices of the graph such that no two adjacent
vertices of the graph are colored with the same color.
Print "Possible" if it is possible to color the graph as mentioned above, else print "Not Possible".
Input
1
32
02
12
2
Output
Possible

62
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:

1) Kiran is a very obedient boy and helping others is a habit of him. He will do any work with dedication
his teacher assigns him a work to generate all permutations of given word. Since he is busy helping
others, you are asked to help him to complete his work on behalf of him. (Use Backtracking Concept)

63
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS
2) Mr. Sai joined for as an assistant at a school where he was given a job to arrange schedules for the
subject n1, n2, n3, n4, n5, n6, n7, n8. Help him schedule the timetable from the given information.
Let this be the schedule:
Here for everyone hour there are many subjects competing. Use backtracking and create a schedule
where each subject is assigned to a specific hour in a day. In the schedule ‘1’ represents that the
subject is competing for that hour.

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured:______ out of_____


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

64
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 10: SUM OF SUBSETS


Date of the Session: / / Time of the Session: to

Pre-Lab:

1) Dark Peace is volunteer in VISION 2K17.ChiefCO gave him a task to complete it before the
CODEGEEKS which is on 11th march. ChiefCo asks DarkPeace to do the work as soon as possible.
So, to complete the task as soon as possible Dark Peace asks you to help him. You will be given two
set of length N and M. Your task is to find whether the subset is present in the first set whose sum of
elements is equal to the member of the set. You must check for every member of the second set. Print
Yes if subset is present and if not present print No and if the member exceeds the maximum sum of
Input
33
174
10 14 4
Output
No -1 Yes
Explanation
For first member no subset gives sum to 10 so we print No. For second since maximum sum is 12
and 14 is greater than 12 so we print -1. For last subset {4} exits whose sum is equal to 4 and hence
we print Yes.

65
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

In-Lab:

1) Geeta is working in a company, and she has n different projects to work on, where every project is
scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You are given the
startTime, endTime and profit arrays, return the maximum profit you can take such that there are no
two projects that she is working on in that given subset with overlapping time range. If she chooses a
project that ends at time a then she will be able to start another project that starts at time b.
Input
startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output
150
Explanation: The subset chosen is the first, fourth and fifth project.
Profit obtained 150 = 20 + 70 + 60.

66
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS
2) The subset sum problem is an important problem in computer science. Below we will provide a simple
algorithm for solving this problem. The challenge is to determine if there is some subset of numbers in
an array that can sum up to some number S. These algorithms can both be implemented to solve Array
Addition I and Array Addition.

Simple (Naive) solution


The algorithm for the exponential time, naive solution, is as follows: First we will generate
every possible set (the power set), and then check if the sum of any of these sets equals the
sum S. For example: arr = [1, 2, 3] sum = 5
All possible sets:[] [1] [2] [3] [1, 2] [1, 3] [2, 3] [1, 2, 3]
We can see that we can get a sum of 5 by adding the elements in the set [2, 3]. To generate all possible
sets of an array, we will implement the following algorithm:
(1) The initial power set only contains the empty set: [[]]
(2) We loop through each element in the array and add it to every element in the powerset.
(3) Then we take the union of these two sets.
(4) Once we get the power set, we check to see if the sum equals our goal S.
Example
arr = [1, 2, 3] sum = 5 sets = [[]]
Step 1: Add 1 to the power set [[], [1]]
Step 2: Add 2 to the power set [[], [1], [1, 2], [2]]
Step 3: Add 3 to the power set [[], [1], [1, 2], [2], [1, 3], [2, 3], [1, 2, 3], [3]]

67
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:
1) Karthik was given a problem in an online interview, but he cannot solve the solution help him solve
the question. There are n students whose ids vary between 0 to 9 digits; two students can have same
id's. You will be given x numbers which also vary from 0 to 9. You need to find the total number of
student id's subsets which contains all the x numbers.
Input
333
1
3
Output
6

68
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) You are offered N pay packages by various companies, Congratulations! You can only select 2
unique groups of packages each with a total of at least K. Select the 2 groups such that you choose
minimum number of companies adding up to the total of K.
Input
arr[] = {2, 4, 5, 6, 7, 8}, K = 16
Output
6
Explanation:
The subsets {2, 6, 8} and {4, 5, 7} are the two smallest subsets with sum K (= 16).
Therefore, the sum of the lengths of both these subsets = 3 + 3 = 6.4

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured:______ out of______


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation: 69


21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 11: BRANCH AND BOUND


Date of the Session: / / Time of the Session: to
Pre-Lab:
1) Match the data structure used to generate branch and bound strategy.

2) You are given a knapsack that can carry a maximum weight of 60. There are 4 items with weights
{20, 30, 40, 70} and values {70, 80, 90, 200}. What is the maximum value of the items you can
carry using the knapsack?

70
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

In-Lab:
1) A Professor is teaching about Binary Numbers. He wants to know all the possible binary numbers of
a given length. Help the Professor to generate all the set of binary strings of length N in ascending
order using Branch and Bound Technique.
Input
N=3
Output
000
001
010
011
100
101
110
111
Explanation:
Numbers with 3 binary digits are
0, 1, 2, 3, 4, 5, 6, 7

71
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) You are in a supermarket shopping for fruits with huge discounts. There are N varieties of fruits
available each with a weight C and discount P. Now, select K fruits in a way that maximizes the
discount. You only have a bag which can carry a weight of W.
Input
N=5
P [] = {2, 7, 1, 5, 3}C [] = {2, 5, 2, 3, 4}, W = 8, K = 2.
Output
12
Explanation:
Here, the maximum possible profit is when we take 2 items: item2 (P[1] = 7 and C[1] = 5) and
item4 (P[3] = 5 and C[3] = 3).
Hence, maximum profit = 7 + 5 = 12

72
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

Post-Lab:
1) Given an array of positive elements, you must flip the sign of some of its elements such that the
resultant sum of the elements of array should be minimum non-negative (as close to zero as possible).
Return the minimum no. of elements whose sign needs to be flipped such that the resultant sum is
minimum non-negative. Note that the sum of all the array elements will not exceed 104.
Input
arr [] = {15, 10, 6}
Output
1
Here, we will flip the sign of 15
and the resultant sum will be 1.

73
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS
2) There are some processes that need to be executed. The amount of load that process causes a server
that runs it, is being represented by a single integer. The total load caused on a server is the sum of the
loads of all the processes that run on that server. You have at your disposal two servers, on which the
mentioned processes can be run. Your goal is to distribute given processes between those two servers
in a way that, the absolute difference of their loads will be minimized.
Given an array of A[] of N integers, which represents loads caused by successive processes, the task is
to print the minimum absolute difference of server loads.
Input
A[] = {1, 2, 3, 4, 5}
Output
1
Explanation:
Distribute the processes with loads {1, 2, 4} on the first server and {3, 5} on the second server, so that
their total loads will be 7 and 8, respectively.
The difference of their loads will be equal to 1.

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured:______ out of _______


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

74
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

LAB SESSION 12: NP-HARD AND NP-COMPLETE


Date of the Session: / / Time of the Session: to
Pre-Lab:

1) Read the following conversation


Jaya: Travelling salesman problem is a NP hard problem.
Hema: I do not think so
Jaya: No, I am so sure that Travelling Salesman problem is a NP hard problem.
Hema: …!!
You are Jaya’s friend. Help her prove her statement.

75
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

2) Consider the two graphs and find out the node cover for the each of the graphs and specify the
maximum node cover.

a)

b)

76
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS

In-Lab:
1) Raju prepares for the examination, but he got stuck into a concept called "NP-HARD AND "NP-
COMPLETE PROBLEMS" on Nondeterministic Algorithms. So, help Raju to score good marks. Help
him to define the Nondeterministic algorithms by sorting an array.

77
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS
2) Karthik and Bavya are trying to implement a program that helps a transportation company use its
container to maximum efficiency, as part of their CS project.
Few objects are more valuable than others. Each object has a certain weight. The transportation
company wants to fill the container so that the value of the container (sum of value of objects in the
container) is maximum, while total weight of the objects does not exceed the container's capacity.
As the outcome is not fixed, this is a non-deterministic problem. This is a knapsack problem as we
must maximize value within the given weight limit.
So, to understand the problem well and implement it, help them in finding non-deterministic knapsack
algorithm.

78
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS
Post-Lab:
1) Hema: Hamiltonian Path is NP-Complete.
Jaya: Well, prove that!
Hema: I will prove and let you know.
Help Hema to try and prove that Hamilton Path is NP-Complete

79
21CS2214RB DESIGN & ANALYSIS OF ALGORITHMS
2) Hemanth was unable to answer the following question in exam. Here is the question, help Hemanth to
find P1 solution. Find the total cost to find the P1 solution

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured:_______ out of ________


Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:


80

You might also like