Sei sulla pagina 1di 144

LAB WORKBOOK

17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Team ADA
K L UNIVERSITY | ANALYSIS AND DESIGN OF ALGORITHMS – 17CS3114
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

LABORATORY WORKBOOK

STUDENT NAME
REG. NO
YEAR
SEMESTER
SECTION
FACULTY

1
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Table of contents
Organization of the STUDENT LAB WORKBOOK ..................................................................................... 4
Lab 1: ....................................................................................................................................................... 7
Prerequisite:........................................................................................................................................ 7
Pre-Lab Task: ....................................................................................................................................... 7
In-Lab Task: ....................................................................................................................................... 11
Post-Lab Task: ................................................................................................................................... 18
Lab 2: ..................................................................................................................................................... 23
Prerequisite:...................................................................................................................................... 23
Pre-Lab Task: ..................................................................................................................................... 23
In-Lab Task: ....................................................................................................................................... 27
Post-Lab Task: ................................................................................................................................... 30
Lab 3: ..................................................................................................................................................... 36
Prerequisite:...................................................................................................................................... 36
Pre-Lab Task: ..................................................................................................................................... 36
In-Lab Task: ....................................................................................................................................... 40
Post-Lab Task: ................................................................................................................................... 45
Lab 4: ..................................................................................................................................................... 51
Prerequisite:...................................................................................................................................... 51
Pre-Lab Task: ..................................................................................................................................... 51
In-Lab-Task: ....................................................................................................................................... 54
Post-Lab Task: ................................................................................................................................... 58
Lab 5: ..................................................................................................................................................... 65
Prerequisite:...................................................................................................................................... 65
Pre-Lab Task: ..................................................................................................................................... 65
In-Lab Task: ....................................................................................................................................... 68
Post-Lab Task: ................................................................................................................................... 72
Lab 6: ..................................................................................................................................................... 75
Prerequisite:...................................................................................................................................... 75
Pre-Lab Task: ..................................................................................................................................... 75
In-Lab Task: ....................................................................................................................................... 77
Post-Lab-Task: ................................................................................................................................... 80
Lab 7: ..................................................................................................................................................... 84
Prerequisite:...................................................................................................................................... 84
Pre-Lab Task: ..................................................................................................................................... 84

2
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task: ....................................................................................................................................... 86


Post-lab Task: .................................................................................................................................... 90
Lab 8: ..................................................................................................................................................... 93
Prerequisite:...................................................................................................................................... 93
Pre-Lab Task: ..................................................................................................................................... 93
In-Lab Task: ....................................................................................................................................... 95
Post-lab Task: .................................................................................................................................... 99
Lab 9: ................................................................................................................................................... 103
Prerequisite:.................................................................................................................................... 103
Pre-Lab Task: ................................................................................................................................... 103
In-Lab Task: ..................................................................................................................................... 105
Post-lab Task: .................................................................................................................................. 109
Lab 10: ................................................................................................................................................. 112
Prerequisite:.................................................................................................................................... 112
Pre-Lab Task: ................................................................................................................................... 112
In-Lab Task: ..................................................................................................................................... 114
Post-lab Task: .................................................................................................................................. 117
Lab 11: ................................................................................................................................................. 121
Prerequisite:.................................................................................................................................... 121
Pre-LabTask: .................................................................................................................................... 121
In-Lab Task: ..................................................................................................................................... 124
Post-Lab Task: ................................................................................................................................. 127
Lab 12: ................................................................................................................................................. 131
Prerequisite:.................................................................................................................................... 131
Pre-Lab Task: ................................................................................................................................... 131
In-Lab Task: ..................................................................................................................................... 134
Post-Lab Task: ................................................................................................................................. 138

3
17CS3114 ANALYSIS AND DESIGN 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-Hourclosed laboratory period. Within this structure, each
laboratory includes three parts: Prelab, In-lab, and Post-lab.
a. Pre-Lab
The Prelab 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. Prelab Students attending a two-hour closed laboratory
are expected to make a good-faith effort to complete the Prelab 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 Prelab exercises. The intent is to give constructive
feedback so that students leave the lab with working Prelab software - a significant
accomplishment on their part. During the second hour, students complete the In-lab
exercise to reinforce the concepts learned in the Prelab. Students leave the lab
having received feedback on their Prelab 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.

4
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2018-19 EVEN SEMESTER LAB CONTINUOUS EVALUATION


Pre-Lab
In-Lab(30M) Viva
Sl (15M) Total Faculty
Date Experiment Name Logic Impleme Execution LOGIC EXECUTIO RESUL ANALYSI Voce
No (50M) Signature
(5M) ntation (5M) (10M) N (10M) T (5M) S (5M) (5M)
(5M)

5
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2018-19 EVEN SEMESTER LAB CONTINUOUS EVALUATION


Pre-Lab
In-Lab(30M) Viva
Sl (15M) Total Faculty
Date Experiment Name Logic Impleme Execution LOGIC EXECUTIO RESUL ANALYSI Voce
No (50M) Signature
(5M) ntation (5M) (10M) N (10M) T (5M) S (5M) (5M)
(5M)

10

11

12

6
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SUBJECT CODE: 17CS3114
ANALYSIS AND DESIGN OF ALGORITHMSWORKBOOK

Lab 1:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:

1) Find the time complexity of the following:


a. long Fibonacci(int n)
{
if(n==1 || n==2)
return 1;
else
return Fibonacci(n-1)+Fibonacci(n-2);
}

b. long factorial(int n)
{
If(n==0)
return 1;
else
return n*factorial(n-1);
}

7
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Viswa must arrange students in ascending order according to height wise he needs
to arrange students before the teacher comes. So, help Viswa to arrange students
accordingly (Imagine students as elements in array)
hint:Quick sort helps to sort array in best time complexity
https://beginnersbook.com/2015/02/quicksort-program-in-c/

Sample Input:
Enter n value:5
Enter height of student 1
34
Enter height of student 2
45
Enter height of student 3
47
Enter height of student 4
50
Enter height of student 5
65
Sample Output:
The heights of students in order 34 45 47 50 65

8
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

9
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) What is the time, space complexity of following code?


int a = 0, b = 0;
for (i = 0; i < N; i++) {
a = a + rand();
}
for (j = 0; j < M; j++) {
b = b + rand();
}

10
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:

1) The previous challenges covered Insertion Sort, which is a simple and intuitive
sorting algorithm with a running time of O(n2). In these next few challenges, we're
covering a divide-and-conquer algorithm called Quicksort (also known as Partition
Sort). This challenge is a modified version of the algorithm that only addresses
partitioning. It is implemented as follows
Step 1: Divide
Choose some pivot element p,and partition your unsorted array,arr, into three
smaller arrays: left, right, and equal, where each element in left<p , each element in
right>p, and each element in equal=p .
For example: Assume arr=[5,7,4,3,8]
The pivot is at arr[0]=5
is divided into ,left={4,3} ,equal={5} and right={7,8}.
Putting them all together, you get {4,3,5,7,8}. Another valid solution is {3,4,5,8,7}.
Given arr and p=arr[0] , partition arr into left, right, and equal using the Divide
instructions above. Then print each element in left followed by each element in
equal, followed by each element inright on a single line. Your output should be
space-separated and does not have to maintain ordering of the elements within the
three categories
Function Description:
Complete the quickSort function in the editor below. It should return an array of
integers as described above.
quickSort has the following parameter(s):

 arr: an array of integers where arr[0] is the pivot element.

Input format:
The first line contains n, the size of the array arr .
The second line contains n space-separated integers describing arr (the unsorted
array). The first integer (corresponding to arr[0] ) is your pivot element, p.
Constraints:
1≤n≤1000
-1000 ≤ arr[i] ≤ 1000 where 0 ≤ i < n

11
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

All elements will be unique.


Output format:
On a single line, print the partitioned numbers (i.e.: the elements in left , then the
elements in equal, and then the elements in right). Each integer should be separated
by a single space.
Sample Input:
5
45372
Sample Output:
32457
Explanation:
arr=[4,5,3,7,2] Pivot: p=arr[0]=4.
left={};equal={4} ;right={}
arr[1]=5>p, so it's added to right .
left={};equal={4} ;right={5}
arr[2]=3<p, so it's added to left .
left={3};equal={4} ;right={5}
arr[3]=7>p, so it's added to right.
left={3};equal={4} ;right={5,7}
arr[4]=2<p, so it's added to left.
left={3,2};equal={4} ;right={5,7}
We then print the elements of left, followed by equal, followed by right , we get: 3 2
4 5 7.
You don't need to maintain ordering, so another valid solution would be 2 3 4 5 7.

12
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

13
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

14
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Uday decided to send emails to his N friends he have some mails of his friends he
should check whether mails of his friends are klu mails or not and then after finding
it arrange the names of his friends given with mail id's in alphabetical order help him
by writing a program. Klu mail end with @kluniversity.in. First total number of
friends N next N lines as name and mail id's. Constraints 2<=N<=30 Each of the first
names consists of lower case letters[a-z]only. Each of the email IDs consists of lower
case letters[a-z],@ and . only. The length of the first name is no longer than 20. The
length of the email ID is no longer than 50. Print an alphabetical order of Uday
friends who have valid klu mails
Sample Input:
Uday Uday@kluniversity.in
ram ram@julia.me
harry harry@kluniversity.in
dhp dhp@kluniversity.in
karthik karthik@gmail.com
hari hari@kluniversity.in
Sample Output:
dhp
hari
harry
Uday

15
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

16
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) Print the elements of an array in the decreasing frequency if 2 numbers have same
frequency then print the one which came first.
https://www.geeksforgeeks.org/sort-elements-by-frequency/

Sample Input:
arr[] = {2, 5, 2, 8, 5, 6, 8, 8}
Sample Output:
arr[] = {8, 8, 8, 2, 2, 5, 5, 6}

17
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-Lab Task:

1) A shopkeeper who is too lazy to arrange things, has got an order of n boxes. A
customer visits the shop and wants to check the kth smallest box. As he is too lazy to
arrange the boxes, help him to find the kth smallest box in minimum number of
steps.
Sample Input:
Enter Kth box to find: 6
Enter no of boxes: 10
Enter the box Numbers that was arranges in a row
3 2 6 7 8 1 5 9 12 4
Sample Output:
Kth smallest Box is: 6

18
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Given two arrays A1[] and A2[], sort A1 in such a way that the relative order among
the elements will be same as those are in A2. For the elements not present in A2,
append them at last in sorted order.
Sample Input:
A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
A2[] = {2, 1, 8, 3}
Sample Output:
A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}
https://www.geeksforgeeks.org/sort-array-according-order-defined-another-array/

19
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

20
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) You are given an array A of length N. For any given integer X, you need to find an
integer Z strictly greater than X such that Z is not present in the array A. You need to
minimize the value of Z.
https://www.hackerearth.com/practice/algorithms/sorting/quick-sort/practice-
problems/algorithm/yet-to-keep-6f89250c/

Sample Input:
52
2 7 5 9 15
3
9
Sample Output:
4
10

21
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 2:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:

1) For each of the following recurrences, give an expression for the runtime T (n) if the
recurrence can be solved with the Master Theorem. Otherwise, indicate that the
Master Theorem does not apply.
a. T (n) = 8*T(n/3) + n2
b. T(n) = 8*T(n/2)+(n3/log n)
c. T (n) = 3T (n/5) – n2 log n
d. T (n) = 3*T (n/3) + √ n
https://www.youtube.com/watch?v=OynWkEj0S-s&list=PLDN4rrl48XKpZkf03iYFl-
O29szjTrs_O&index=27

23
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Trace the way of Strassen’s matrix multiplication for 4*4 matrix


https://decodediary.com/2018/09/29/strassens-matrix-multiplication-4x4-example/

Sample-Input:
A = [[2 0 1 3] B = [[5 3 7 2]
[2 1 0 4] [4 1 9 6]
[3 2 4 1] [3 2 0 4]
[1 3 2 4]] [2 1 8 3]]
Sample-Output:
C = [[19 9 38 17]
[26 11 55 22]
[37 18 47 37]
[35 14 66 40]]

24
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

25
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) Ravi is a customer purchased n items in the shop their cost is n integers. Help the
shop keeper to find the cost of items and sort the elements based on the price.
Develop a program whose time complexity is O(n^2) for all the inputs
https://www.hackerrank.com/contests/17cs1102/challenges/3c-implement-
selection-sort/submissions/code/1309501097

Sample-Input:
5
1 9 7 3 10
Sample-Output:
sorted list is
1
3
7
9
10
sum is:30

26
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:

1) Ramesh learnt how to do 2x2 matrix multiplications manually in his intermediate


education. Right now, he is doing his engineering. In one of his Mathematics classes
he was required to do matrix multiplications but the instructor of the course asked
the class to do this multiplication in a different way than usual (multiply the row with
the columns). He asked them to do it using the ‘Strassen’s matrix multiplication
method’. Help him complete this task by developing an algorithm and writing a code
to implement the algorithm
https://www.sanfoundry.com/c-program-implement-strassens-algorithm/

Sample-Input:
Enter the 4 elements of first matrix: 1 2 3 4
Enter the 4 elements of second matrix: 3 4 5 7
The first matrix is
1 2
3 4
The second matrix is
3 4
5 7
Sample-Output:
After multiplication using
13 18
40

27
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

28
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Given an array of positive integers. Sort the given array in decreasing order of
number of factors of each element, i.e., element having the highest number of
factors should be the first to be displayed and the number having least number of
factors should be the last one. Two elements with equal number of factors should be
in the same order as in the original array.
https://www.geeksforgeeks.org/sort-elements-basis-number-factors/

Sample-Input:
{5, 11, 10, 20, 9, 16, 23}
Sample-Output:
6 10 9 5 11 23

29
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-Lab Task:

1) Cell phone distributer works for x company must distribute phones to all cities in a
state. There are ‘n’ cities where their locations (Co-ordinates) are mentioned. Some
cities have flexibility to share products with other cities. So, distributer must select
such cities through following conditions:
Find the point with left most city (minimum x co-ordinate) let’s say, min_x and
similarly the point with right most city (maximum x co-ordinate), max_x.
Make a line joining these two points, say L. This line will divide the whole state into
two parts. Take both the parts one by one and proceed further.
For a part, find the city P with perpendicular maximum distance from the line L
Repeat these above steps by taking min_x, p as one line and max_x, p as other
recursively until there are no maximum points seen.
Help distributer to find the cities (Print all the maximum points).
IF no such output is possible print Convex hull not possible

https://www.geeksforgeeks.org/convex-hull-set-1-jarviss-algorithm-or-wrapping/

Sample-Input:
8
03
11
22
44
00

30
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

12
31
33

Sample-Output:
The points in Convex Hull are:
(0, 0) (0, 3) (3, 1) (4, 4)

31
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

32
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Given two arrays of integers, compute the pair of values (one value in each array)
with the smallest (non-negative) difference. Return the difference.
https://www.geeksforgeeks.org/smallest-difference-pair-values-two-unsorted-
arrays/

Sample-Input:
A[] = {l, 3, 15, 11, 2}
B[] = {23, 127, 235, 19, 8}
Sample-Output:
3
That is, the pair (11, 8)

33
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) Given a matrix A= { 9,7,5,11,12,2,14,3,10,6}. Sort the matrix using Quick sort .Trace
the matrix and print the matric at each iteration.

34
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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:

35
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 3:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:
1) Draw the fixed size table and calculate the bits for the message transferred and also
the bits to store the table for the given message -” BCCABBDAAECBBBAEDDBC” of
length 25 that is transfer to the destination from source side. Find the how many bits
reduced by using the Huffman code in fixed size space.
https://www.youtube.com/watch?v=co4_ahEDCho

36
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Today is the day of joining for an employee named Ramesh as it is the first day, he
doesn’t know the way to office. Then he opens his phone and checks the route, but
he is confused with a lot of routes. So, help Ramesh to reach office in a shortest
path.
Sample-Input:
Enter no. of vertices:5
Enter the adjacency matrix:
03400
30562
45000
06000
02000
Enter the starting node:3
Sample-Output:
cost of node= 6
Path=1<-3

37
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

38
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) Implement a state space tree for the following table using knapsack by greedy
method
object 1 2 3 4 5 6 7
profit 10 5 15 7 6 18 3
weights 2 3 5 7 1 4 1
Constraint: m=15(bag size)
https://www.youtube.com/watch?v=oTTzNMHM05I

39
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:

1) Marc loves cupcakes, but he also likes to stay fit. Each cupcake has a calorie count,
and Marc can walk a distance to expend those calories. If Marc has eaten j cupcakes
so far, after eating a cupcake with c calories he must walk at least 2^j*c miles to
maintain his weight. For example, if he eats 3 cupcakes with calorie counts in the
following order: [5,10,7], the miles he will need to walk are
(2^0*5)+(2^1*10)+(2^2*7)=5+20+28=53.This is not the minimum ,though, so we
need to test others orders of consumption. In this case, our minimum miles is
calculated as (2^0*10)+(2^1*7)+(2^2*5)=10+14+20=44,
Given the individual calorie counts for each of the cupcakes, determine the minimum
number of miles Marc must walk to maintain his weight. Note that he can eat the
cupcakes in any order.
https://www.hackerrank.com/challenges/marcs-cakewalk/problem

Sample Input:
3
132
Sample Output:
11

40
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

41
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Problem Statement for RangeEncoding

You are given a int[] arr that contains a set of positive integers. The elements in arr
are all distinct and they are given in increasing order.
A range is a finite set of consecutive integers. Formally, for any two positive integers
a ≤ b the range [a,b] is defined to be the set of all integers that lie between a and b,
inclusive. For example, [3,3] = {3} and [4,7] = {4,5,6,7}.
You want to represent the set given in arr as a union of some ranges. Return the
minimum number of ranges you need.
Constraints
- arr will have between 1 and 50 elements, inclusive.
- Each element of arr will be between 1 and 50.
- The elements in arr will be in strictly increasing order.
Examples
0) {1,2,3,4,5,6,7,8,9,10}
Returns: 1
We can represent this set as a single range [1,10].
1) {1,6,10,20,32,49}
Returns: 6
In this case we have to use 6 different ranges, each containing just a single number.
2) {2,4,5,6,8,9,10,11,12,15}
Returns: 4
This set of integers can be represented as the union of four ranges: [2,2], [4,6],
[8,12], and [15,15].
3) {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47}
Returns: 14
4) {10,11,12,13,14,15,20,21,22,23,25,27,28,29,30,31,32,33}
Returns: 4
5) {33}
Returns: 1
https://community.topcoder.com/stat?c=problem_statement&pm=14592

42
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

43
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) Veni can do any work assigned to her within an hour for which she will be paid.
There are p people who want their work to be finished in a given time deadline. They
all pay a certain amount for their work to be done. Develop a program to help Veni
to choose the works so that she could earn max profit.
https://github.com/OpenGenus/quark/blob/master/code/code/greedy_algorithms/s
rc/job_sequencing/job_sequencing.cpp

Sample-Input:
Enter number of persons: 5
A 260
B 1100
C 320
D 240
E 120
Sample-Output:
Following is maximum profit sequence of jobs
BAC

44
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-Lab Task:

1) Assume there are M persons and each person needs exactly one book from library.
For each person, you are given the start time and end time (both inclusive) during
which that person will return the book. Find the minimum number of books
required. Print the minimum number of books required.
https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-
algorithms/practice-problems/algorithm/minimum-cabs-0798cfa5/

Sample-Input:
6
1020
16 0 21 30
9 30 13 0
21 30 22 30
21 30 22 30
12 0 12 30
Sample-Output:
3

45
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

46
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) There are n jobs each associated with a deadline and profit and your task is to earn
maximum profit.1st line contains n value, next n lines contain job id, deadline, profit,
1st line contains sequence of jobs,2nd line contains maximum profit.
https://www.dyclassroom.com/greedy-algorithm/job-sequencing-problem-with-
deadline

Sample-Input:
5
j1 2 70
j2 1 110
j3 3 30
j4 2 50
j5 1 30
Sample-Output:
Required Jobs: j2 --> j1 --> j3
Max Profit: 210

47
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

48
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) Pandit has a dream to be fit but he loves sweet he had a choice to eat sweet but to
stay fit which is when he climb 3^j steps he can stay fit here j is calorie for each
sweet he ate.
https://www.hackerrank.com/challenges/greedy/problem

Sample-Input:
3
498
Sample-Output:
207
(3^3*4+3^2*8+3^1*9)=207

49
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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:

50
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 4:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:

1) Draw the fixed size table and calculate the bits for the message transferred and also
the bits to store the table for the given message -” BCCABBDAAECBBBAEDDBC” of
length 20 that is transfer to the destination from source side. And also find the how
many bits reduced by using the Huffman code in fixed size space.
https://www.youtube.com/watch?v=qthY6wkuj-g

51
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Find the weight of a minimum spanning tree of the following graphs?


a)

b) w=[ [0 1 8 1 4] [1 0 12 4 9 ] [8 12 0 7 3] [1 4 7 0 2] [4 9 3 2 0]
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/

52
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) Write the major difference between Prims and Kruskal’s algorithm and write the
various applications on both algorithms and also write pseudo code for both the
algorithms.
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/

53
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab-Task:

1) A plan is built to connect different towers in a city using cables of some lengths. The
lengths of cables are given. You should modify the plan such that usage of cable
length is minimum. Your first task is to print the total length of cables used to
connect all towers (use Kruskal’s algorithm). A tower is said to be terminal tower
when it is connected with only one other tower. Print “YES” if there is only one
tower between any two terminal towers, otherwise print “NO”.

In the above spanning-tree A, D, F are terminal towers and the answer is “NO”
because there are more than one tower between any two terminal towers.
https://www.geeksforgeeks.org/kruskals-algorithm-simple-implementation-for-
adjacency-matrix/
Sample-Output:
Edge 0:(0, 2) cost:1
Edge 1:(2, 4) cost:2
Edge 2:(2, 3) cost:3
Edge 3:(0, 1) cost:5
Edge 4:(1, 5) cost:6
Edge 5:(4, 6) cost:9
Minimum cost= 26
NO

54
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

55
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Prim’s algorithm to construct a minimum spanning tree starting with node A, write
the sequence of edges represents a possible order in which the edges would be
added to construct the minimum spanning tree using both prims and Kruskal’s
method.

56
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) Using Dijkstra’s algorithm create tables that stores the values of shortest distance to
all the nodes from the present node

https://www.thecrazyprogrammer.com/2014/03/dijkstra-algorithm-for-finding-
shortest-path-of-a-graph.html

57
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-Lab Task:

1) Nanda decides to go to a tour. So he himself prepared a map and he started from the
city where he lives in, determine the lengths of the shortest paths from the starting
city to all other cities in the map. If a city is unreachable, its distance is -1. Cities will
be numbered consecutively as from and to , and edges will have varying distances or
lengths.
Sample-Input:
Enter no. of cities:5
Enter the cost matrix:
03400
30562
45000
06000
02000
Enter the starting city:3
Sample-Output:
Distance of node0=9
Path=0<-1<-3
Distance of node1=6
Path=1<-3
Distance of node2=11
Path=2<-1<-3
Distance of node4=8
Path=4<-1<-3

58
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

59
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Given a graph which consists of several edges connecting its nodes, find a subgraph
of the given graph with the following properties: The subgraph contains all the nodes
present in the original graph. The subgraph is of minimum overall weight (sum of all
edges) among all such subgraphs. It is also required that there is exactly one,
exclusive path between any two nodes of the subgraph. Find the total weight or the
sum of all edges in the subgraph using prim’s algorithm.
Sample-Input:
Enter the number of nodes:5
Enter the adjacency matrix:
03400
30562
45000
06000
02000
Sample-Output:
Edge 1:(1 2) cost:3
Edge 2:(2 5) cost:2
Edge 3:(1 3) cost:4
Edge 4:(2 4) cost:6
Minimum cost=15

60
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

61
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

3) A student wants to reach his college in time so that he wouldn’t be punished in


college. There are many landmarks while going to college like temple, post office,
hospital etc. He can travel through many routes to reach college. Help him to find
shortest path to reach the college and every landmark from his house. (Assume that
the distances can be negative also.) Two integers V(number of vertices/landmarks)
and E(number of paths/distances b/w landmarks).Next E lines consists three values
source, destination and path cost. Print shortest distance for each landmark
https://github.com/mkfeuhrer/spoj-solutions/blob/master/CSTREET.cpp

Sample-Input:
58
0 1 -1
024
123
132
142
325
311
4 3 -3
Sample-Output:
Vertex Distance from Source
0 0
1 -1
2 2
3- 2
4 1

62
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

63
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 5:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:

1) Fill the following table using 0/1 knapsack by applying dynamic programming
W=8, N=4
0 1 2 3 4
Profit 0 1 2 5 6
Weight 0 2 3 4 5

0 1 2 3 4 5 6 7 8

0 0 0 0 0 0 0 0 0 0

1 0 0 1 1 1 1 1 1 1

2 0 0 1 2 2 3 3 3 3

3 0 0 1 2 5 5 6 7 7

4 0 0 1 2 5 6 6 ? ?

65
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) A bank contains N of accounts in it. The account which have loan will have negative
sign before their bank balance. The account with no loan will be considered as a
savings account and have just a positive number. Here the bank wants to find the no
of subarrays in which the number of loan accounts in that subarray is equal to the
number of savings accounts in same subarray. The input consists of two lines. First
line denotes N - size of array. Second line contains N space separated positive
integers denoting the elements of array A. Print a single integer, denoting the
number of subarrays
https://www.hackerearth.com/practice/algorithms/dynamic-
programming/introduction-to-dynamic-programming-1/practice-
problems/algorithm/odd-even-subarrays-72ad69db/

Sample Input:
4
1 -2 1 -2
Sample Output:
4

66
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

67
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:

1) There are n items with some weights and corresponding values and a bag of capacity
W. The items should be placed in the bag in such a way that the total value is
maximum and total weight should be less than knapsack capacity. In this problem 0-
1 means that we can’t put the items in fraction. Either put the complete item or
ignore it. find the solution for this problem in C using dynamic programming.
https://www.hackerearth.com/practice/notes/knapsack-algorithm-problem-solved-
using-dynamic-programming/
Sample Input:
Enter number of items:3
Enter value and weight of items:
1 45
2 56
3 40
Enter size of knapsack:40
Sample Output:
3

68
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

69
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) You are watching a soccer match, and you wonder what the probability is that at
least one of the two teams will score a prime number of goals. The game lasts 90
minutes, and to simplify the analysis, we will split the match into five-minute
intervals. The first interval is the first five minutes, the second interval is the next five
minutes, and so on. During each interval, there is a skillOfTeamA percent probability
that team A will score a goal, and a skillOfTeamB percent probability that teamB will
score a goal. Assume that each team will score at most one goal within each interval.
Return the probability that at least one team will have a prime number as its final
score.
Notes:
- The returned value must be accurate to within a relative or absolute value of 1E-9.

- A prime number is a number that has exactly two divisors, 1 and itself. Note that 0 and 1
are not prime.

Constraints:
- skillOfTeamA will be between 0 and 100, inclusive.
- skillOfTeamB will be between 0 and 100, inclusive.
Examples:
1. 50 50
Returns: 0.5265618908306351
2. 100 100
Returns: 0.0
3. 12 89
Returns: 0.677204716884016

https://community.topcoder.com/stat?c=problem_statement&pm=10033

70
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

71
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-Lab Task:

1) Given an array of n positive integers. Write a program to find the sum of maximum
sum subsequence of the given array such that the integers in the subsequence are
sorted in increasing order
https://www.geeksforgeeks.org/maximum-sum-increasing-subsequence-dp-14/

Sample-Input:
1, 101, 2, 3, 100, 4, 5
Sample-Output:
106

72
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Given an array of integers where each element represents the max number of steps
that can be made forward from that element. Write a function to return the
minimum number of jumps to reach the end of the array (starting from the first
element). If an element is 0, then cannot move through that element.
https://www.geeksforgeeks.org/minimum-number-of-jumps-to-reach-end-of-a-
given-array/

Sample-Input:
1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9
Sample-Output:
4

73
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 6:

Date of the Session: ___/___/___ Time of the Session_____to______

Prerequisite:

Pre-Lab Task:

1) Sita plans to go on a trip to different places. She has the information about distances
from one place to any other place. With this information help Sita by suggesting a
route map to travel such that she travels the shortest possible route, visiting every
city exactly once and returns to the starting point

75
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Each Directed Edge is labelled with capacity. Use the Ford-Fulkerson algorithm to
find the maximum flow

76
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:
1) Raju has got 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 have to 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 have to print the root of that Optimal Binary search Tree.
Tasks:
(i)You should Find the Cost of the optimal BST by considering all the keys and print
the value in a new Line.
(ii)Find and print the root of the Optimal BST formed by the range of indices (keys
index range) given by each sub-query. The first line contains integer 'n' which
describes the size of the keys. The second line contains values of keys. The third Line
contains values about frequencies of each keys. The fourth Line is an integer 'm'
which describes no of queries. The following lines contains two integers describing
the range for each query. Print the cost Of the Optimal BST by considering all the
keys. For each Query print the root of the Optimal BST based on the given range
https://www.geeksforgeeks.org/optimal-binary-search-tree-dp-24/

Sample-Input:
4
12 10 20 21
8 34 50 1
2
03
01
Sample-Output:
Cost of Optimal BST is 144
20
10

77
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

78
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Ram won a lottery ticket with which he plans to go on a trip to different places. He
knows the distance from one place to any other place. With this information write a
program to help ram to travel shortest possible route that visits every city exactly
once and returns to the starting point.

79
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-Lab-Task:

1) You are packing for a vacation on the seaside and you are going to carry only one bag
with capacity ‘m’. You also have ‘n’ items that you might want to take with you to
the seaside. Unfortunately, you cannot fit all of them in the knapsack so you will
have to choose. For each item you are given its size and its value. You want to
maximize the total value of all the items you are going to bring. What is this
maximum total value? On the first line you are given ‘n’. n lines follow with two
integers on each line describing one of your items. The first number is the value of
the and the next is item the size of the item. The last line contains capacity of the
bag ‘m’. You should output a single integer on one like - the total maximum value
from the best choice of items for your trip.
https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/

Sample-Input:
Enter total number of items :5
Enter the values and sizes of 5 items:8 1
42
03
52
32
Enter the total bag capacity :4
Sample-Output:
Maximum Profit = 13

80
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

81
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) There is a bus in a district which will travel all cities which starts from and end with
district headquarters (which is 0 position), it will go in smallest path possible to travel
but due to rain some roads are damaged. if there is a damaged road then print “IT
WILL EFFECT “or else print”NO EFFECT”.
Sample-Input:
4
0, 10, 15, 20
10, 0, 35, 25
15, 35, 0, 30
20, 25, 30, 0
1
01
Sample-Output:
IT WILL EFFECT

82
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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:

83
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 7:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:

1) Draw a state space tree for the backtracking of sum of subsets.


Given n=3
Weights= {10,5,15}
T=15
https://www.geeksforgeeks.org/subset-sum-backtracking-4/

84
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Trace 4-queen problem using backtracking.

https://www.youtube.com/watch?v=xFv_Hl4B83A

85
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:

1) Yaaaay, haven’t you heard the news? Bakaloria results are out! And Reem had very
good grades. Finally, she can go to IT college and pursue her childhood dream of
becoming a great programmer.
Reem is very excited about her college, she already started learning programming.
Today she was learning about a very well-known problem, the 8-Queens problem
(you never saw that coming, didn't you?) she has wrote a program to generate all
the possible situations of the queens, but as a novice programmer she found it hard
to check whether if these situations are valid. As usual you come to her rescue and
offer to help with this hard task!
Now you are stuck with this task: Given the positions of 8 queens on a regular chess
board, determine if this situation is valid.
A valid situation is a configuration of the 8 queens where no queen can strike any
other queen.
On a standard 8 × 8 chess board, a queen can strike any other queen on it's row,
column, or two diagonals.
Input Format:
The first line of input has one integer T the number of test cases your program must
process.
Each of the next T lines contains the positions of 8 queens. A position of a queen is
described as one character [A - H] (the column of the queen), followed by one
number [1 - 8] (the row of the queen)
For example: "A4" represents a queen at the first column and the fourth row.
(see sample input for more details)
Output Format:
For each test case print one line containing the word Valid if the configuration is
valid, or Invalid otherwise.
Sample Input:
2
A1 B5 C8 D6 E3 F7 G2 H4
C3 E4 C4 E1 C4 F4 A8 G6
Sample Output:
Valid
Invalid
http://codeforces.com/problemset/gymProblem/100947/B

86
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

87
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2). Print all possible subsets that are selected from a given array whose sum adds up to a
given number K. Consider the set contains non-negative values.
Sample Input:
7 // size of array
10 7 5 18 12 20 15 // array elements
35 // K
Sample Output:
5 10 20
5 12 18
7 10 18
15 20
https://www.geeksforgeeks.org/subset-sum-backtracking-4/

88
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

89
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-lab Task:

1) Given an array ‘arr’ consisting of integers, the task is to find the non-empty subset
such that its sum is closest to zero i.e. absolute difference between zero and the sum
is minimum.
Input:
arr[] = {2, 2, 2, -4}
Output:
0
Explanation:
arr[0] + arr[1] + arr[3] = 0
That’s why answer is zero.
https://www.geeksforgeeks.org/subset-with-sum-closest-to-zero/

90
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Given n pairs of parentheses, write a function to generate all combinations of well-


formed parentheses of length 2*n.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
Make sure the returned list of strings is sorted.
https://www.geeksforgeeks.org/print-all-combinations-of-balanced-parentheses/

91
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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:

92
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 8:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:

1) Color the following graph so that color of each vertex shouldn’t match with the color
of its adjacent vertices.

https://www.youtube.com/watch?v=RSSfO0lnEp8

93
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) What are the elements in the visited list after executing following code? [BFS]
def my_func(graph, root):
visited, queue = set(), collections.deque([root])
visited.add(root)
while queue:
vertex = queue.popleft()
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
Take graph as

And root as A.
https://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/
https://www.programiz.com/dsa/graph-bfs

94
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:

1) Given an undirected graph and a number m, determine if the graph can be colored
with at most m colors such that no two adjacent vertices of the graph are colored
with the same color. Here coloring of a graph means the assignment of colors to all
vertices.
Input:

 A 2D array graph[V][V] where V is the number of vertices in graph and


graph[V][V] is adjacency matrix representation of the graph. A value graph[i][j] is
1 if there is a direct edge from i to j, otherwise graph[i][j] is 0.
 An integer m which is the maximum number of colors that can be used.
Output:
An array color[V] that should have numbers from 1 to m. color[i] should represent
the color assigned to the ith vertex. The code should also return false if the graph
cannot be colored with m colors.
https://www.geeksforgeeks.org/m-coloring-problem-backtracking-5/

95
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

96
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Rajesh want to know the popular tourist places around him in the radius of 3 Km.
from his current position. The city map is given in the form a graph and for simplicity
always assume his position as starting node 0 and distance between adjacent two
nodes is taken as 1Km. Your task is to print all the neighboring tourist places.
Implement this problem using Depth first search.
Sample Input:
5 // Number of nodes
01000
00100
00010
00001
00000
0 // Source node or Starting node
Sample Output:
1 at depth 0
2 at depth 1
3 at depth 2
4 at depth 3
https://www.sanfoundry.com/java-program-implement-depth-limited-search/

97
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

98
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-lab Task:

1) Find shortest safe route in a path with landmines.


Input:
A 12 x 10 matrix with landmines marked as 0

[1 1 1 1 1 1 1 1 1 1]
[1 0 1 1 1 1 1 1 1 1]
[1 1 1 0 1 1 1 1 1 1]
[1 1 1 1 0 1 1 1 1 1]
[1 1 1 1 1 1 1 1 1 1]
[1 1 1 1 1 0 1 1 1 1]
[1 0 1 1 1 1 1 1 0 1]
[1 1 1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1 1 1]
[0 1 1 1 1 0 1 1 1 1]
[1 1 1 1 1 1 1 1 1 1]
[1 1 1 0 1 1 1 1 1 1]
Output:
Length of shortest safe route is 13
https://www.geeksforgeeks.org/find-shortest-safe-route-in-a-path-with-landmines/

99
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

100
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Print all palindromic partitions of a string.


Input:
S = “bcc”
Output:
[["b", "c", "c"], ["b", "cc"]]
Input:
S = “geeks”
Output:
[["g", "e", "e", "k", "s"], ["g", "ee", "k", "s"]]

101
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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:

102
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 9:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:

1) Describe the advantages and disadvantages of 0/1 Knapsack’s branch and bound
problem.
https://www.geeksforgeeks.org/0-1-knapsack-using-branch-and-bound/

103
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Consider the following table with given weights and respective profit in context to
0/1 knapsack problem using branch and bound. Draw the state space tree and solve
the problem.

Pi Wi
10 2
10 4
12 6
18 9
https://www.youtube.com/watch?v=yV1d-b_NeK8&list=PLDN4rrl48XKpZkf03iYFl-
O29szjTrs_O&index=70

104
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:

1) Solve 0/1 Knapsack using Branch and Bound


Sample output:
Maximum possible profit = 235
https://www.geeksforgeeks.org/implementation-of-0-1-knapsack-using-branch-and-bound/

105
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) A string t is called an anagram of the string s, if it is possible to rearrange letters in t


so that it is identical to the string s. For example, the string "aab" is an anagram of
the string "aba" and the string "aaa" is not.
The string t is called a substring of the string s if it can be read starting from some
position in the string s. For example, the string "aba" has six substrings: "a", "b", "a",
"ab", "ba", "aba".
You are given a string s, consisting of lowercase Latin letters and characters "?". You
are also given a string p, consisting of lowercase Latin letters only. Let's assume that
a string is good if you can obtain an anagram of the string p from it, replacing the "?"
characters by Latin letters. Each "?" can be replaced by exactly one character of the
Latin alphabet. For example, if the string p = «aba», then the string "a??" is good,
and the string «?bc» is not.
Your task is to find the number of good substrings of the string s (identical substrings
must be counted in the answer several times).
Input Format:
The first line is non-empty string s, consisting of no more than 105 lowercase Latin
letters and characters "?". The second line is non-empty string p, consisting of no
more than 105 lowercase Latin letters. Please note that the length of the string p can
exceed the length of the string s.
Output Format:
Print the single number representing the number of good substrings of string s.
Two substrings are considered different in their positions of occurrence are
different. Thus, if some string occurs several times, then it should be counted the
same number of times.
Sample Input:
bb??x???
aab
Sample Output:
2
Sample Input:
ab?c
acb
Sample Output:
2
Note:

106
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Consider the first sample test. Here the string s has two good substrings: "b??" (after we
replace the question marks we get "baa"), "???" (after we replace the question marks
we get "baa").
Let's consider the second sample test. Here the string s has two good substrings: "ab?"
("?" can be replaced by "c"), "b?c" ("?" can be replaced by "a").

107
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

108
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-lab Task:
1) Pantelija was given a sequence of positive integers a1,a2,aNa1,a2,aN. Let's define
the gcd value of this sequence as the number of its non-empty contiguous
subsequences with greatest common divisor strictly greater than 11. The greatest
common divisor of any contiguous subsequence al,al+1,aral,al+1,ar (1≤l≤r≤N1≤l≤r≤N)
is the greatest positive integer which divides each element of this
subsequence.Pantelija wants to maximize the gcd value of this sequence. In order to
do that, he may choose a valid index ii, an integer bb (1≤b≤5⋅1051≤b≤5⋅105, since he
does not like large numbers) and change the element aiai to bb. What is the
maximum possible gcd value he can obtain?
Sample input:
5

4 5 10 3 7

Sample output:

https://www.codechef.com/problems/GCDS

109
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Implement 8 puzzle Problem using Branch And Bound approach.

Sample Input:
initial
123
560
784
Final
123
586
074
Sample Output:
123
560
784

123
506
784

123
586
704

123
586
074
https://www.geeksforgeeks.org/8-puzzle-problem-using-branch-and-bound/

110
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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:

111
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 10:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:

1) Draw the state space tree for the following travelling salesman problem using branch
and bound approach. Given a set of cities and distance between every pair of cities,
the problem is to find the shortest possible tour that visits every city exactly once
and returns to the starting point

https://www.geeksforgeeks.org/traveling-salesman-problem-using-branch-and-bound-2/

112
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Explain the each and every step using state spaces and identify the reduced costs
also for each and every node.

https://www.youtube.com/watch?v=1FEP_sNb62k

1 2

4 3

113
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:

1) A family is planning for a tour .That family wanted to visit some cities the cities are
Paris, London, New York, Los Angeles and we are giving the distance between each
pair of cities, the problem is to find the shortest possible route that visits every city
exactly once and returns to the starting point. Solve the below problem using
Travelling Salesman problem using Branch and Bound using programming
Sample Input:
Enter No. of cities:
4
Enter the cost matrix
Enter elements of row:1
0 10 35 30
Enter elements of row:2
10 0 30 15
Enter elements of row:3
35 30 0 30
Enter elements of row:4
30 15 30 0
Sample Output:
The cost list is
0 10 35 30
10 0 30 15
35 30 0 30
30 15 30 0
Optimal Solution:
The path is:
1-->2-->4-->3-->1
Minimum cost:90
http://www.ccodechamp.com/c-program-for-travelling-salesman-problem-using-branch-
and-bound/

114
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

115
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Solve the Job Assignment Problem using Branch and Bound


Sample output:
Assign Worker A to Job 1
Assign Worker B to Job 0
Assign Worker C to Job 2
Assign Worker D to Job 3
Optimal Cost is 13
https://www.geeksforgeeks.org/job-assignment-problem-using-branch-and-bound/

116
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-lab Task:

1) Write a program to find the optimal solution for the Traveling Salesperson problem
and then solve the same problem instance using any approximation algorithm and
determine the error in the approximation.
Sample Input:
Enter No. of cities:
4
Enter the cost matrix
Enter elements of row:1
0136
Enter elements of row:2
1023
Enter elements of row:3
3201
Enter elements of row:4
6310
Sample Output:
The cost list is
0 1 3 6
1 0 2 3
3 2 0 1
6 3 1 0
Optimal Solution:
The path is:
1-->2-->4-->3-->1
Minimum cost:8
Approximated Solution:
The path is:
1-->2-->3-->4-->1

117
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Minimum cost:10
Error in approximation is approximated solution/optimal solution=1.250000

http://cs-in-engineering.blogspot.com/2016/03/lab-program-9-implement-any-
scheme-to.html

118
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) A Ministry for Defense sent a general to inspect the Super-Secret Military Squad
under the command of the Colonel Super-duper. Having learned the news, the
colonel ordered to all n squad soldiers to line up on the parade ground. By the
military charter the soldiers should stand in the order of non-increasing of their
height. But as there's virtually no time to do that, the soldiers lined up in the
arbitrary order. However, the general is rather short-sighted and he thinks that the
soldiers lined up correctly if the first soldier in the line has the maximum height and
the last soldier has the minimum height. Please note that the way other solders are
positioned does not matter, including the case when there are several soldiers
whose height is maximum or minimum. Only the heights of the first and
the last soldier are important. For example, the general considers the sequence of
heights (4, 3, 4, 2, 1, 1) correct and within one second the colonel can swap any two
neighboring soldiers. Help him count the minimum time needed to form a line-up
which the general will consider correct.

Sample Input:
4

33 44 11 22

Sample Output:

http://codeforces.com/contest/144/problem/A

119
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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:

120
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 11:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:

1) Trace KMP algorithm for given pattern

Sample Input:

txt[] = "AABAACAADAABAABA"

pat[] = "AABA"

https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/

121
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Manish has got the task to frame a speech for his professor at the university at the
Annual sports meet. But the problem is that the professor has speech dyslexia and he
can't speak the words clearly which have vowels in them. So Manish has to avoid such
words and has to minimize their usage in the speech letter. Your task is to help Manish
mark the vowels in the words so that he can minimize their use. You are given a string S
consisting of lower-case letters only. You need to count the number of vowels in the
string S.

Input Format:

The first line will contain an integer T denoting the number of test cases. The
following T lines will contain a string S in lower case letters only.

Output Format:

Print the number the vowels in the string S.

Sample Input:

hashes

Sample Output:

https://www.hackerearth.com/practice/algorithms/string-algorithm/basics-of-string-
manipulation/practice-problems/algorithm/vowels/

122
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

123
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:

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 the time taken by fun()
clock_t t;
t = clock();
fun();
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("fun() took %f seconds to execute \n", time_taken);
return 0;
}

https://www.youtube.com/watch?v=V5-7GzOfADQ

124
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

125
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) You were given a pattern and a string. If the pattern is present in the string then it is
known as magical string (if present at least once). If the string is not present in the
string find the minimum number of changes that are to be made to make it magical
string. If it a magical string print the number of times the pattern is present in the
string.
Example: string- “abaaababaabbabb”
Pattern- “abbb”
The minimum changes are 1. (changing a as b at 13th index) the string can be
converted into a magical string.
https://www.youtube.com/watch?v=qQ8vS2btsxI

126
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-Lab Task:

1) Given a string 'S' , u need to tell whether it is 'sumit's string or not'.A string is called
'Sumit's String' , if distance between adjacent character is 1.Consider that the
alphabets are arranged in cyclic manner from 'a' to 'z'. distance between any
character 'x' and 'y' will be defined as minimum number of steps it takes 'x' to reach
'y'. Here, character 'x' can start moving clockwise or anti-clockwise in order to reach
at position where character 'y' is placed.

Print 'YES' if it is Sumit's string else print 'NO', for each test case.

Sample Input:
3
aba
zza
bcd
Sample Output:
YES
NO
YES
https://www.hackerearth.com/practice/algorithms/string-algorithm/basics-of-string-
manipulation/practice-problems/algorithm/sumits-string/

127
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

128
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

1) Given an encrypted message, Erwin encodes it the following way: Removes the median
letter of the word from the original word and appends it to the end of the encrypted
word and repeats the process until there are no letters left. A median letter in a word is
the letter present in the middle of the word and if the word length is even, the median
letter is the left one out of the two middle letters.
Given an encoded string, write a program to decode it.

Input Format:

The first line of input contains T, the number of test cases.


Each test case contains a String S, denoting the encoded word.

Output Format:

Print the decoded word for each test case in a separate line.

Sample Input:

wrien

reen

Sample Output:

erwin

eren

Explanation

In the first test case, Erwin encoded the String "erwin". At first, he wrote down the
letter 'w' after which the string became "erin", he then wrote down 'r' and the
remaining string was "ein", he then wrote 'i' and the string became "en" and so on
he wrote down 'e' and 'n' to get the encoded string as "wrien".

https://www.hackerearth.com/practice/algorithms/string-algorithm/basics-of-string-
manipulation/practice-problems/algorithm/decode-1-6eab2976/

129
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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:

130
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Lab 12:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite:

Pre-Lab Task:

1) How hash values are used in Rabin Karp algorithm and explain with an example?
https://www.geeksforgeeks.org/rabin-karp-algorithm-for-pattern-searching/

131
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Given a string consisting of alphabets and digits, find the frequency of each digit in
the given string.
Input Format:
The first line contains a string, which is the given number.
Constraints:
All the elements of num are made of English alphabets and digits.
Output Format:
Print ten space-separated integers in a single line denoting the frequency of each
digit from to.
Sample Input:
a11472o5t6
Sample Output:
0210111100
https://www.hackerrank.com/challenges/frequency-of-digits-1/problem

132
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

133
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

In-Lab Task:

1) Today is Ram and Joe's birthday. There friends have designed a birthday song for
them. This song includes both Ram and joe name in between. They want to know
how many times those names are repeated in song. write a program to print how
many times those names printed in the song. Take the string and whose name
should be checked as input. If 0 print how many times Ram name is repeated and 1
for Joe. Use Rabin karp method to solve this problem which is more efficient than
brute force method.
https://www.youtube.com/watch?v=qQ8vS2btsxI

134
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

135
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Lisa is a school student teacher gave her an assignment to check whether the pattern
is there or not in a given text and also she mentioned that it is have solve by using
kmp algorithm so when a mismatch come other some matches in your search if she
print the number of letters that we can neglect before then she will get good marks
so help her by writing a code.
Sample Input:
ABABDABACDABABCABAB
ABABCABAB
Sample Output:
we don’t match before 2 letters because they will match anyway
we don’t match before 0 letters because they will match anyway
we don’t match before 1 letter because they will match anyway
we don’t match before 0 letters because they will match anyway
Found pattern at index 10

136
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

137
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

Post-Lab Task:

1) You are given a binary string S. You need to transform this string into another string
of equal length consisting only of zeros, with the minimum number of operations. A
single operation consists of taking some prefix of the string S and flipping all its
values. That is, change all the 0s in this prefix to 1s, and all the 1s in the prefix to 0s.
You can use this operation as many number of times as you want over any prefix of
the string.
Input:
The only line of the input contains the binary string, S.
Output:
Output a single line containing one integer, the minimum number of operations that
are needed to transform the given string S into the string of equal length consisting
only of zeros.
Sample Input:
01001001
Sample Output:
6
Explanation:
For the given sample case, let us look at the way where we achieved minimum
number of operations.
Operation 1: You flip values in the prefix of length 8 and transform the string into
10110110
Operation 2: You flip values in the prefix of length 7 and transform the string into
01001000
Operation 3: You flip values in the prefix of length 5 and transform the string into
10110000
Operation 4: You flip values in the prefix of length 4 and transform the string into
01000000
Operation 5: You flip values in the prefix of length 2 and transform the string into
10000000
Operation 6: You flip values in the prefix of length 1 and finally, transform the string
into 00000000
https://www.codechef.com/problems/PREFINVS

138
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

139
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

140
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

2) Given an alphanumeric string made up of digits and lower-case Latin characters only,
find the sum of all the digit characters in the string.
Input Format:
The first line of the input contains an integer T denoting the number of test cases.
Then T test cases follow.
Each test case is described with a single line containing a string S, the alphanumeric
string
Output Format:
For each test case, output a single line containing the sum of all the digit characters
in that string.
Input:
1
ab1231da
Output:
7
Explanation:
The digits in this string are 1, 2, 3 and 1. Hence, the sum of all of them is 7.
https://www.codechef.com/problems/KOL15A

141
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

(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:

142
17CS3114 ANALYSIS AND DESIGN OF ALGORITHMS

143