0% found this document useful (0 votes)
40 views11 pages

Lab Session 06-2000031745

This document contains a lab session report by Sriyaa Narisety with student ID 2000031745. The report includes pre-lab and in-lab questions on topics related to algorithms including 0-1 knapsack problems, shortest path algorithms, maximum thieves that can be caught, maximum area of water container, and scheduling jobs to maximize total profit. Post-lab questions involve scheduling jobs to maximize profit and assigning mice to holes to minimize time for the last mouse. Solutions to the questions are provided using Java code.

Uploaded by

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

Lab Session 06-2000031745

This document contains a lab session report by Sriyaa Narisety with student ID 2000031745. The report includes pre-lab and in-lab questions on topics related to algorithms including 0-1 knapsack problems, shortest path algorithms, maximum thieves that can be caught, maximum area of water container, and scheduling jobs to maximize total profit. Post-lab questions involve scheduling jobs to maximize profit and assigning mice to holes to minimize time for the last mouse. Solutions to the questions are provided using Java code.

Uploaded by

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

LAB SESSION 06:

Sriyaa Narisety
2000031745

Pre-Lab:

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

Solution:
0-1 knapsack problem cannot be solved by the greedy method because it is
enabled to fill the knapsack to full capacity .

so here greedy algorithm is not optimal.

0-1 knapsack problem is solved by Dynamic programming approach.

Fractional knapsack problem is different from 0-1 knapsack problem

2) Categorize the Following as single source or multiple source shortest path algorithms.
Floyd-Warshall algorithm
Dijkstra’s algorithm –
Bellman-Ford algorithm –

Solution:
Floyd-Warshall Algorithm : It is an algorithm for finding the shortest path
between all the pairs of vertices in a weighted
graph. It is an single source shortest path algorithm.

Dijkstra’s algorithm : The Dijkstra Shortest Path algorithm computes the


shortest path between nodes.It is a single-
source shortest path algorithm.

Bellman-Ford algorithm : This algorithm works correctly when some of the edges of
directed graph G may have negative weight. It is
a single-source shortest path algorithm .

3) List down various shortest path greedy algorithms.

Solution :
• Prim’s Minimal Spanning Tree Algorithm
• Travelling Salesman Problem
• Graph – Map Coloring
• Kruskal’s Minimal Spanning Tree Algorithm
• Dijkstra’s Minimal Spanning Tree Algorithm
• Graph – Vertex Cover
• Knapsack Problem
• Job Scheduling Problem
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.

Solution:
import java.util.*;
import java.io.*;

class Main
{
// Returns maximum number of thieves
// that can be caught.
static int policeThief(char arr[], int n, int k)
{
int res = 0;
ArrayList<Integer> thi = new ArrayList<Integer>();
ArrayList<Integer> pol = new ArrayList<Integer>();

// store indices in the ArrayList


for (int i = 0; i < n; i++) {
if (arr[i] == 'P')
pol.add(i);
else if (arr[i] == 'T')
thi.add(i);
}

// track lowest current indices of


// thief: thi[l], police: pol[r]
int l = 0, r = 0;
while (l < thi.size() && r < pol.size()) {

// can be caught
if (Math.abs(thi.get(l) - pol.get(r)) <= k) {
res++;
l++;
r++;
}

// increment the minimum index


else if (thi.get(l) < pol.get(r))
l++;
else
r++;
}
return res;
} public static void main(String args[])
{
int k, n;
char arr1[] =new char[] { 'P', 'T', 'T',
'P', 'T' };
k = 1;
n = arr1.length;
System.out.println("Maximum thieves caught: "
+policeThief(arr1, n, k));

}
}
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

Solution:
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
Following is maximum
profit sequence of jobs is c, a

Solution:
import java.util.*;

class Main
{
// Each job has a unique-id,
// profit and deadline
char id;
int deadline, profit;

// Constructors
public Main() {}

public Main(char id, int deadline, int profit)


{
this.id = id;
this.deadline = deadline;
this.profit = profit;
}

// Function to schedule the jobs take 2


// arguments arraylist and no of jobs to schedule
void printJobScheduling(ArrayList<Main> arr, int t)
{
// Length of array
int n = arr.size();
Collections.sort(arr,
(a, b) -> b.profit - a.profit);

// To keep track of free time slots


boolean result[] = new boolean[t];

// To store result (Sequence of jobs)


char job[] = new char[t];

// Iterate through all given jobs


for (int i = 0; i < n; i++)
{
// Find a free slot for this job
// (Note that we start from the
// last possible slot)
for (int j
= Math.min(t - 1, arr.get(i).deadline - 1);
j >= 0; j--) {

// Free slot found


if (result[j] == false)
{
result[j] = true;
job[j] = arr.get(i).id;
break;
}
}
}

// Print the sequence


for (char jb : job)
{
System.out.print(jb + " ");
}System.out.println();
}

// Driver code
public static void main(String args[])
{
ArrayList<Main> arr = new ArrayList<Main>();

arr.add(new Main('a', 4, 20));


arr.add(new Main('b', 1, 10));
arr.add(new Main('c', 1, 40));
arr.add(new Main('d', 1, 30));
// Function call
System.out.println("Following is maximum "
+ "profit sequence of jobs");

Main job = new Main();

// Calling function
job.printJobScheduling(arr, 3);
}
}
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

Solution:
import java.util.* ;

public class Main


{
// Returns minimum time required to place mice
// in holes.
public int assignHole(ArrayList<Integer> mice,
ArrayList<Integer> holes)
{
if (mice.size() != holes.size())
return -1;

/* Sort the lists */


Collections.sort(mice);
Collections.sort(holes);

int size = mice.size();

/* finding max difference between ith mice and hole */


int max = 0;
for (int i=0; i<size; i++)
if (max < Math.abs(mice.get(i)-holes.get(i)))
max = Math.abs(mice.get(i)-holes.get(i));

return Math.abs(max);
}

/* Driver Function to test other functions */


public static void main(String[] args)
{
Main gfg = new Main();
ArrayList<Integer> mice = new ArrayList<Integer>();
mice.add(4);
mice.add(-4);
mice.add(2);
ArrayList<Integer> holes= new ArrayList<Integer>();
holes.add(4);
holes.add(0);
holes.add(5);
System.out.println("The last mouse gets into "+
"the hole in time: "+gfg.assignHole(mice, holes));
System.out.println("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:

You might also like