0% found this document useful (0 votes)
54 views

DAA Lab Manual Simplified Version

This document is a lab manual for the Design and Analysis of Algorithms course at The Oxford College of Engineering, Department of Information Science and Engineering. It provides details about the course objectives, description, list of experiments to be performed, and instructions for implementing various algorithms and data structures like stacks, queues, sorting, and graph algorithms using Java. The experiments cover topics such as recursion, divide and conquer, dynamic programming, greedy algorithms, and NP-complete problems.

Uploaded by

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

DAA Lab Manual Simplified Version

This document is a lab manual for the Design and Analysis of Algorithms course at The Oxford College of Engineering, Department of Information Science and Engineering. It provides details about the course objectives, description, list of experiments to be performed, and instructions for implementing various algorithms and data structures like stacks, queues, sorting, and graph algorithms using Java. The experiments cover topics such as recursion, divide and conquer, dynamic programming, greedy algorithms, and NP-complete problems.

Uploaded by

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

The oxford college of Engineering ,Dept.

of ISE DAA Lab Manual (18CSL47)


---------------------------------------------------------------------------------------------------------------------------------------------

THE OXFORD COLLEGE OF ENGINEERING


Hosur Road, Bommanahalli,Bangalore-560068.

DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING

LABORATORY MANUAL[2018 SCHEME]


[UPDATED 2021-22]

SUBJECT NAME & CODE: DESIGN AND ANALYSIS OF ALGORITHMS


LAB(18CSL47)
SCHEME-B.E(ISE) : 2018 SCHEME
SEMESTER : IV
FACULTY INCHARGE : Mrs .S. VISALINI, ASST.PROF, TOCE

----------------------------------------------------------------------------------------------------------------------------------------------------
1
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------

DESIGN AND ANALYSIS OFALGORITHMLABORATORY


[AsperChoiceBased CreditSystem(CBCS)scheme]
(Effectivefromtheacademicyear 2016-2017)
SEMESTER – IV
SubjectCode 15CSL47 IA Marks 20
NumberofLectureHours/Week 01 I+ 02 P ExamMarks 80
TotalNumberofLectureHours 40 ExamHours 03
CREDITS – 02
Courseobjectives:Thiscoursewillenablestudentsto
 Design andimplementvariousalgorithms inJAVA
 Employvariousdesignstrategiesforproblemsolving.
 Measureand comparetheperformance ofdifferentalgorithms.
Description
Design,develop,andimplementthe specifiedalgorithms forthefollowingproblems
usingJavalanguage under LINUX/Windowsenvironment.Netbeans/Eclipse IDEtoolcan be
usedfordevelopmentand demonstration.
Experiments
1 A Create aJavaclasscalledStudentwiththefollowingdetails as variableswithinit.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
WriteaJavaprogramto
createnStudentobjectsandprinttheUSN,Name,Branch,andPhoneoftheseobjectswithsuitab
leheadings.
B Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.
2 A Design a superclass called Staff with details as StaffId, Name, Phone, Salary.
Extend this class by writing three subclasses namely Teaching (domain,
publications), Technical (skills), and Contract (period). Write a Java program to read
and display at least 3 staff objects of all three categories.
B Write a Java class called Customer to store their name and date_of_birth. The
date_of_birth format should be dd/mm/yyyy. Write methods to read customer data
as and display as using StringTokenizer class considering the delimiter character as
“/”.
3 A Write a Java program to read two integers a andb. Compute a/b and print, when b is
not zero. Raise an exception when b is equal to zero.
B Write a Java program that implements a multi-thread application that has three
threads. First thread generates a random integer for every 1 second; second thread
computes the square of the number andprints; third thread will print the value of
cube of the number.

----------------------------------------------------------------------------------------------------------------------------------------------------
2
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
4 Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to
sort. Plot a graph of the time taken versus non graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using Java
how the divide and-conquer method works along with its time complexity analysis: worst
case, average case and best case.

5 Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program for varied values of n> 5000, and record the time taken to
sort. Plot a graph of the time taken versus non graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using Java
how the divideand-conquer method works along with its time complexity analysis: worst
case, average case and best case.
6 Implement in Java, the 0/1 Knapsack problem using
(a) Dynamic Programming method.
(b)Greedymethod.
7 From a given vertex in a weighted connected graph, find shortest paths to other vertices
usingDijkstra's algorithm. Write the program in Java.
8 Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal'salgorithm. Use Union-Find algorithms in your program.
9 Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's
algorithm.
10 Write Java programs to
(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
(b) ImplementTravellingSalesPerson problemusingDynamicprogramming.

11 Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n
positive integers whose SUM is equal to a given positive integer d. For example, if S ={1,
2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message,
if the given problem instance doesn't have a solution.

12 Design and implement in Java to find all Hamiltonian Cycles in a connected undirected
Graph G of n vertices using backtracking principle.

----------------------------------------------------------------------------------------------------------------------------------------------------
3
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------

1a.
Create a Java class called Student with the following details as variables within it. (i) USN (ii) Name (iii)
Branch (iv) Phone Write a Java program to create nStudent objects and print the USN, Name, Branch, and
Phone of these objects with suitable headings.
importjava.util.Scanner;

public class Student


{
intusn, phone;
String name,branch;

voidreadStudentDetails(inti)
{
System.out.println("Enter Usn Name Branch Phone No. of student "+(i+1));
Scanner s = new Scanner(System.in);
usn = s.nextInt();
name = s.next();
branch = s.next();
phone = s.nextInt();
}

voiddisplayStudentDetails()
{
System.out.println("usn+”\t”+name+”\t”+branch+”\t”+phone);
}
public static void main(String[] args)
{
System.out.println("Enter number of students : ");
Scanner s1 = new Scanner(System.in);
int n = s1.nextInt();
Student stud[] = new Student[n];
for(inti = 0 ; i<num ; i++)
{
stud[i] = new Student();
stud[i].readStudentDetails(i);
}
System.out.println("---------------------------------------------------------------------");
System.out.format"USN\tName\tBranch\tPhone_No");
System.out.println("---------------------------------------------------------------------");
for(inti = 0 ; i< n ; i++)
{
stud[i].displayStudentDetails();

----------------------------------------------------------------------------------------------------------------------------------------------------
4
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
}
}
}

Output :

1b.
Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods to
demonstrate its working.
importjava.util.Scanner;
import static java.iang.asystem.exit;

publicclass Stack {
ints[] = new int[5];
int top;

Stack(){
top=-1;
}

voidpush()
{
if(top==s.length-1)
{
System.out.println("Stack Overflow");
return;
}

----------------------------------------------------------------------------------------------------------------------------------------------------
5
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
else
{
System.out.println("Enter element to be pushed");
Scanner scan=newScanner(System.in);
int item=scan.nextInt();
s[++top]=item;
System.out.println("Item pushed: "+s[top]);
}
}
void pop()
{
if(top==-1)
{
System.out.println("Stack underflow");
return;
}
else
{
intele=s[top--];
System.out.println("popped element is "+ele);
}
}
void display()
{
if(top == -1)
System.out.println("Stack is empty");
for(inti=top ;i>=0;i--)
{
System.out.println(s[i]);
}
}
publicstaticvoid main(String args[])
{
Stack sc=newStack();
intch;

do
{
System.out.println("1:push\t2:pop\t3:display\t4:exit\t\n Enter your choice");
Scanner s = new Scanner(System.in);
ch=s.nextInt();
switch(ch)
{
case 1: sc.push();
break;
case 2: sc.pop();
break;
case 3:System.out.println(“the stack elements are”);
sc.display();
break;
case 4:exit(0);
default: System.out.println(“enter choice from 1 to 4”);
}
}while(ch>0);
----------------------------------------------------------------------------------------------------------------------------------------------------
6
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
}
}

Output

2a.
Design a superclass called Staff with details as StaffId, Name, Phone, Salary. Extend this class by writing
three subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write a
Java program to read and display at least 3 staff objects of all three categories.
importjava.util.Scanner;

classStaffmain {
int StaffId,Phone,Salary;
String name;

----------------------------------------------------------------------------------------------------------------------------------------------------
7
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
Scanner scan = newScanner(System.in);

Void read_staff_details()
{
StaffId=scan.nextInt();
name=scan.next();
Phone=scan.nextInt();
Salary=scan.nextInt();
}
}

class Teaching extendsStaffmain{


String domain;
intno_publication;

voidread_domain_publication()
{
Super.read_staff_details();
domain=scan.next();
no_publication=scan.nextInt();

}
voiddisplay_domain_publictaion()
{
System.out.print(StaffId+"\t"+Name+"\t"+ Phone+"\t"+Salary+"\t"+domain+"\t"+no_publication);
System.out.println("\n");

}
}
public class Technical extends Staffmain{
String skills;
voidread_skills()
{
Super .read_staff_details();
skills=scan.next();
}
voiddisplay_skills()
{
System.out.print(StaffId+"\t"+Name+"\t"+ Phone+"\t"+Salary+"\t"+skills);
System.out.println("\n");

}
}
publicclass Contract extendsStaffmain{
int period;
voidread_contract_period()
{
Super .read_staff_details();
period=scan.nextInt();

}
voiddisplay_contract_period()
{
System.out.println(StaffId+"\t"+Name+"\t"+ Phone+"\t"+Salary+"\t"+period);
----------------------------------------------------------------------------------------------------------------------------------------------------
8
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
System.out.println("\n");

}
}
publicclass Staff {
publicstaticvoid main(String[] args)
{
int n1, n2, n3;
Scanner scan= newScanner(System.in);
System.out.println("How many number of Teaching Staff details do you wish to enter\n");
int n1=scan.nextInt();
Teachingteach[]=new Teaching[n1];
System.out.println("How many number of Technical Staff details do you wish to enter\n");
int n2=scan.nextInt();
Technicaltech[]=new Technical[n2];
System.out.println("How many number of contract Staff do you wish to enter");
int n3=scan.nextInt();
Contract cont[]=new Contract[n3];
for(inti=0;i<n1;i++)
{
System.out.println("EnterSt_id\tName\tPh_no\tsalary\tdomain\tno_publictaion of
teaching staff "+(i+1));
teach[i]=new Teaching();
teach[i].read_domain_publication();
}
for(inti=0;i<n2;i++) {
System.out.println("Enter St_id\tName\tPh_no\tsalary\tskills of technical staff"+
(i+1));
tech[i]=new Technical();
tech[i].read_skills();

}
for(inti=0;i<n3;i++)
{
System.out.println("Enter St_id\tName\tPh_no\tsalary\tContract period of contract
staff” +(i+1));
cont[i]=new Contract();
cont[i].read_contract_period();
}
if(n1>0){
System.out.println("Teaching staff details are \n");
System.out.println("--------------------------------------------------------");
System.out.println("St_id\tName\tPh_no\tsalary\tdomain\tno_publictaion");
System.out.println("--------------------------------------------------------");
for(inti=0;i<n1;i++)
{
teach[i].display_domain_publictaion();
}
else
{
System.out.println("no teaching staff details found");
}
if(n2>0){
----------------------------------------------------------------------------------------------------------------------------------------------------
9
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
System.out.println("--------------------------------------------------");
System.out.println("Technical staff details are \n");
System.out.println("--------------------------------------------------");
System.out.println("St_id\tName\tPh_no\tsalary\tskills\n");
System.out.println("--------------------------------------------------");
for(inti=0;i<n2;i++)
{
tech[i].display_skills();
}
else
{
System.out.println("no technical staff details found \n");
}
if(n3>0)
{
System.out.println("--------------------------------------------------");
System.out.println("Contract staff details are \n");
System.out.println("--------------------------------------------------");
System.out.println("St_id\tName\tPh_no\tsalary\tContract period");
System.out.println("---------------------------------------------------");
for(inti=0;i<n3;i++)
{
cont[i].display_contract_period();
}
{
System.out.println("no contract staff details found \n");
}

}
}
Output
How many number of Teaching Staff details do you wish to enter
1
How many number of Technical Staff details do you wish to enter
1
How many number of contract Staff do you wish to enter
1
Enter St_id Name Ph_no salary domain no_publictaion of teaching staff 1
Reena
123
34567
1321
CSE
2
Enter St_id Name Ph_no salary skills of technical staff 1
Seena
67
2342
3242
C
Enter St_id Name Ph_no salary Contract period of contract staff 1
1

----------------------------------------------------------------------------------------------------------------------------------------------------
10
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
34543
213
3242
2
Teaching staff details are
--------------------------------------------------------
Name St_id Ph_no salary domain no_publictaion
--------------------------------------------------------
Reena 123 34567 1321 CSE 2
--------------------------------------------------------
Technical staff details are
--------------------------------------------------------
Name St_id Ph_no salary skills
--------------------------------------------------------
Seena 67 2342 3242 C
--------------------------------------------------------
Contract staff details are
--------------------------------------------------------
Name St_id Ph_no salary Contract period
--------------------------------------------------------
1 34543 213 3242 2
--------------------------------------------------------

2b.
Write a Java class called Customer to store their name and date_of_birth. The date_of_birth format should
be dd/mm/yyyy. Write methods to read customer data as and display as using StringTokenizer class
considering the delimiter character as “/”.
import java.util.Scanner;
import java.util.StringTokenizer; public class ReadNameDate {
public static void main(String args[]){
ReadNameDate readNameDate = new ReadNameDate(); String customerData=
readNameDate.readCustomeNameDob();
readNameDate.displayCustomerNameDob(customerData);
}
private String readCustomeNameDob() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter name and DOB in <name,dd/mm/yyyy> format");
String str = scanner.next();
if(!str.startsWith("<") ||!str.endsWith(">"))
{ System.out.println("Please enter it in proper format");
}
return str; }
private void displayCustomerNameDob(String customerData)
{ String st = customerData.substring(0, customerData.length());
StringTokenizer stringTokenizer = new StringTokenizer(st, "<,/>"); String finalString =null;
while(stringTokenizer.hasMoreTokens
()){ if(finalString == null){
finalString = stringTokenizer.nextToken();
}else{
}
}
finalString =finalString+","+stringTokenizer.nextToken();
System.out.println("<"+finalString+">");

----------------------------------------------------------------------------------------------------------------------------------------------------
11
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
}
}
SAMPLE INPUT AND OUTPUT:
Enter name and DOB in <name,dd/mm/yyyy> format <surya,11/12/2000>
<surya,11,12,2000>

3a.
Write a Java program to read two integers a andb. Compute a/b and print, when b is not zero. Raise an
exception when b is equal to zero.
importjava.util.Scanner;
publicclass Division
{
publicstaticvoid main(String[] args)
{
int a, b, res;
Scanner scan = newScanner(System.in);
System.out.print("Enter the values of a& b");
a = scan.nextInt();
b = scan.nextInt();
try
{
res = a/b;
System.out.println("Result = "+res);
}
catch (ArithmeticException e)
{
System.out.println("Can't divide by zero" + e);
return;
}
}
}

Output:
Enter the values of a& b
50
Can't divide by zero
Enter the values of a& b
56 2
Res = 28

----------------------------------------------------------------------------------------------------------------------------------------------------
12
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------

3b.
Write a Java program that implements a multi-thread application that has three threads. First thread
generates a random integer for every 1 second; second thread computes the square of the number andprints;
third thread will print the value of cube of the number.
importjava.lang.Thread;
importjava.util.*;

class SquareThread extends Thread


{
int x2;
SquareThread(int n)
{
x2 = n;
}
public void run()
{
System.out.println("Square of a Number"+x2+"is="+(x2*x2));
}

}
Class CubeThread extends Thread
{
int x3;
public CubeThread(intn)
{
x3 = n;
}
Public void run()
{
System.out.println("Cube of a Number"+x3+"is="+(x3*x3*x3));
}
}
Class RandomThread extends Thread
{
publicvoid run()
{
try
{

----------------------------------------------------------------------------------------------------------------------------------------------------
13
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
While(true)
{
Random r = new Random();
int n = r.nextInt(100);
sleep(1000);
System.out.println("The random number is” + n);
SquareThread t2 = newSquareThread(n);
t2.start();
CubeThread t3 = new CubeThread(n);
t3.start();
}
}
catch (InterruptException e)
{
System.out.println("”EXception!!”);
}
}
}

public class MainClass


{
public static void main(String[] args)
{
RandomThread R = new RandomThread();
R.start();
}
}

Output:
The random number is 49
Square of a number 49 is 2401
Cubeof a number 49 is 117649

4.
Sort a given set of n integer elements using Quick Sort method and compute its time complexity. Run the
program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the time taken versus
non graph sheet. The elements can be read from a file or can be generated using the random number
generator. Demonstrate using Java how the divide and-conquer method works along with its time
complexity analysis: worst case, average case and best case.

importjava.util.*;
classQuickSort
{
int[] x = new int[100];
int[] temp = new int[100];
int n;

voidreadElementsRandomly()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of elements : ");

----------------------------------------------------------------------------------------------------------------------------------------------------
14
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
n = scan.nextInt();
Random r = newRandom();
for(inti = 0 ; i<n ; i++)
x[i] = r.nextInt(100);
System.out.println("Elements are");
printSortedArray();
}

voidqsort(int first, intlast)


{
int temp, pivot, i, j;
if( first<last)
{
pivot=first;
i=first;j=last;
while(i< j)
{
while(x[i] <= x[pivot]&&i< last )
i++;
while(x[j] >x[pivot])
j--;
if(i< j)
{
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
temp = x[pivot];
x[pivot] = x[j];
x[j] = temp;
qsort(first, j-1);
qsort(j+1,last);
}
}
Void printSortedArray()
{
for (int i = 0;i<n ; i++)
System.out.println(x[i] );
}
}
classquickmain
{
Publicstaticvoidmain(String[] args)
{
Long start, end;
QuickSort q = newQuickSort();
//Code for sorting randomly entered numbers
q.readElementsRandomly();
start = System.nanoTime();
q.qsort(0,q.n-1);
end = System.nanoTime();
System.out.println("Sorted elements are”);
----------------------------------------------------------------------------------------------------------------------------------------------------
15
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
long tm = end – start;
System.out.println("Total time taken =" +tm/1000000000+" ms");
}
}

Output.
Enter the number of elements :
7
Elements are
4 55 23 546 12 43 12
Sorted elements
4 12 12 23 43 55 546

Enter number of elements : 5000


Total time taken =2 ms
Enter number of elements : 7000
Total time taken =1 ms
Enter number of elements : 8900
Total time taken =1 ms
Enter number of elements : 50000
Total time taken =8 ms
Enter number of elements : 54788
Total time taken =9 ms
Enter number of elements : 567658
Total time taken =63 ms

5.
Sort a given set of n integer elements using Merge Sort method and compute its time complexity. Run the
program for varied values of n> 5000, and record the time taken to sort. Plot a graph of the time taken versus
non graph sheet. The elements can be read from a file or can be generated using the random number
generator. Demonstrate using Java how the divideand-conquer method works along with its time complexity
analysis: worst case, average case and best case.

importjava.util.*;
publicclassMergeSort
{
public static void merge(int A[], intl,intm, int h)
{
int[] b = new int[100];
inti=l,j=m+1, k=l;
while (i<= m && j < h)
{
if (A[i] <= A[j])
B[k++] = A[i++];
else
B[k++] = A[j++];
}
/* Copy remaining elements of B[] if any */
while (i<= m)
B[k++] = A[i++];
/* Copy remaining elements of C[] if any */
----------------------------------------------------------------------------------------------------------------------------------------------------
16
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
while (j <= h)
[k++] = A[j++];
for(k=l ; k<=h ; k++)
A[k] = b[k];
}
public static voidmergesort(int A[], intl,int h)
{
if(l<=h) return;
int m = (l+h)/2;
mergeSort(a, l, m);
mergeSort(a, m+1, h);
merge(a, l, m, h);
}
Publicstaticvoidmain(String[] args)
{
Scanner s = new Scanner(System.in);
Random r = new Random();
inti, n;
int a[] = new int[20];
long start, end;
System.out.println("Enter number of elements : ");
n = scan.nextInt();
System.out.println("Enter” +n+ “integer nos");
for(i=0 ; i<n ; i++)
a[i]=r.nextInt();
System.out.println(“Entered elements are”);
for(i=0 ; i<n ; i++)
System.out.println(a[i]);
start = System.nanoTime();
mergesort(a,0,n-1);
end = System.nanoTime();
System.out.println("Sorted elements are”);
for(i=0 ; i<n ; i++)
System.out.println(a[i]);
double tm = end – start;
System.out.println("Total time taken =" +tm/1000000000+" ms");
}
}

Output.
Enter the number of elements :
7
Elements are
4 55 23 546 12 43 12
Sorted elements
4 12 12 23 43 55 546
Enter number of elements : 10000
Total time taken =7 ms
Enter number of elements : 32432
Total time taken =11 ms
Enter number of elements : 32465
----------------------------------------------------------------------------------------------------------------------------------------------------
17
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
Total time taken =10 ms
Enter number of elements : 324345
Total time taken =65 ms

6a.
Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method.

importjava.util.*;

publicclassKnapsackDynamic
{
int max(inta,int b)
{
return (a>b)?a:b;
}
publicstaticvoid main(String args[])
{
int m, n, i, j, profit = 0;
intw[] = newint[100], p[] = newint[100], x[] = newint[100], v[] = newint[10][10];
Scanner scan = newScanner(System.in);
System.out.println("Enter the number of objects");
n = scan.nextInt();
System.out.println("Enter the maximum capacity of knapsack");
m = scan.nextInt();
for(i = 1 ; i<= n ; i++)
{
System.out.println("Enter the weights&profits of "+i+ “ objects”);
w[i] = scan.nextInt();
p[i] = scan.nextInt();
}
for(i = 0 ; i<= n ; i++)
{
for(j = 0 ; j <= m; j++)
{
if(i ==0 || j == 0)
v[i][j] = 0;
elseif(w[i] >= j)
v[i][j] = v[i-1][j];
else
v[i][j] = max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
profit=v[i][j];
}
}
System.out.print(“Result profit table is:”);
for(i = 0 ; i<= n ; i++)
{
for(j = 0 ; j <= m; j++)
{
System.out.print(v[i][j]+"\t");
}
System.out.print(“ “);
}
for(i = 0 ; i<= n ; i++)

----------------------------------------------------------------------------------------------------------------------------------------------------
18
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
x[i]=0;
i = n, j = m;
while(i != 0 && j != 0)
{
if(v[i][j] != v[i-1][j])
{
X[i]=1; j = j - w[i];
}
i = i - 1;
}
System.out.println("Objects selected are”);
for(i = 0 ; i<= n ; i++)
{
if(x[i]==1)
System.out.println("”\t”+i);
}
System.out.println("Optimal Solution = “ +profit);
}
}

Output.
Enter the number of objects: 2
Enter the maximum capacity of knapsack: 4
Enter the weights& profits of 1 object: 1 15
Enter the weights& profits of 2 object: 2 20
Result profit table is
0 0 0 0 0
0 15 15 15 15
0 15 20 35 35

Objects selected are: 1 2


Optimal Solution = 35

6b.
Implement in Java, the Knapsack problem using Greedy method.

importjava.util.Scanner;
public class KnapsackGreedy
{
Public static void main(String args[])
{
double n, m, rc=0, temp, profit=0;
inti, j;
double w[] = newdouble[10], p[] = newdouble[10], pw[] = newdouble[10], x[] =
newdouble[100];
Scanner scan = newScanner(System.in);
System.out.println("Enter the number of objects");
n = scan.nextInt();
System.out.println("Enter the maximum capacity of knapsack");
m = scan.nextInt();
for(i = 1 ; i<= n ; i++)
{
System.out.println("Enter the weights&profits of "+i+ “ objects”);
w[i] = scan.nextInt();
----------------------------------------------------------------------------------------------------------------------------------------------------
19
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
p[i] = scan.nextInt();
pw[i]=p[i]/w[i];
}
// code for sorting
for(inti = 0 ; i< n - 1 ; i++ )
{
for(int j = 0 ; j < n - i -1 ; j++)
{
if(pw[j] <pw[j+1])
{
temp = pw[j];
pw[j] = pw[j+1];
pw[j+1] = temp;
temp = w[j];
w[j] = w[j+1];
w[j+1] = temp;
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}

}
System.out.println("PW array”);
System.out.println("\tProfit\tWeight\tPW");
for(inti = 0 ; i< n ; i++)
{
System.out.println("\t"+p[i]+"\t"+w[i]+"\t"+pw[i]);
}
for(i = 0 ; i<n ; i++)
x[i]=0;
rc=m;
for(i = 0 ; i<n &&rc> 0 ; i++)
{
if(w[i] >rc)
x[i]= rc/w[j];
else
x[i] = 1;
profit += x[i] * p[i];
System.out.println(“profit is”+ profit+"\t"+ x[i]+"\t"+ +p[j]);
rc =rc - w[j];
}
System.out.println("Maximum profit = "+profit);
}

Output.
Enter the number of objects: 2
Enter the maximum capacity of knapsack: 5
Enter the weights& profits of 1 object: 1 2
Enter the weights& profits of 2 object: 3 4
PW array
Profit Weight PW
----------------------------------------------------------------------------------------------------------------------------------------------------
20
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
2.0 1.0 2.0
4.0 3.0 1.333
Profit is: 2.0 1.0 2.0
Profit is: 6.0 1.0 4.0
Maximum profit = 6.0

7.
From a given vertex in a weighted connected graph, find shortest paths to other vertices usingDijkstra's
algorithm. Write the program in Java.

importjava.util.*;

publicclassDijktras
{
publicstaticvoiddijkstra_soln(int n, intsrc, int cost[][])
{
int min, i, j, u;
int d = newint[100] ;
int v = newint[100];

for(i=1; i<=n; i++)


d[i]=cost[src][i];
for(i=1; i<=n; i++)
{
min = 999, u=0;
for(j = 1; j<= n; j++)
{

if(!v[i]==0 && d[i] < min)


{
min = d[i];
u = j;
}
}
v[u] = 1;
// code to find adjacent vertices to u
for(j = 1 ; j <= n ; j++ )
{
if(v[uj==0 && d[u]+cost[u][j] < d[j])
d[j] = d[u]+cost[u][j];
}
}
for(i=1; i<=n; i++)
System.out.print("src + “” +i+” = ”+d[i]);
}
publicstaticvoid main(String args[])
{
Scanner scan = newScanner(System.in);
inti, j, n, src;
System.out.print("Enter the number of vertices in the Graph : ");
n = scan.nextInt();
System.out.print("Enter the source vertex : ");
src = scan.nextInt();
System.out.println("Enter the weight matrix (enter 999 if no edge exists)");
----------------------------------------------------------------------------------------------------------------------------------------------------
21
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
int cost[][] = new int[10][10];
int v = new int[100];
for(i = 1 ; i<= n ; i++)
{
for( j = 1 ; j <= n ; j++)
cost[i][j] = scan.nextInt();
v[i] = 0;
}
System.out.print("Single source shortest path solution");
dijkstra_soln(n, src, cost);
}
}
Output.
Enter the number of vertices in the Graph : 4
Enter the source vertex : 1
Enter the weight matrix (enter 999 if no edge exists)
0 1 5 2
1 0 999 999
5 999 0 3
2 999 3 0

Single source shortest path solution


11 = 0
12 = 1
13 = 5
14 = 2

8.
Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal'salgorithm. Use
Union-Find algorithms in your program.
importjava.util.*;

publicclassKruskal
{
publicint p[] = new int[10];
publicint cost[][] = new int[10][10];
publicint find(int v)
{
while (p[v] != 0)
v = p[v];
return v;
}
publicvoid union(int u,int v)
{
if(i<j)
p[j] = i;
else
p[i] = j;
}
voidkruskal_soln(int n)
{
inti,j, min, u, v, a=0,b=0, ne=0, mincost=0;

while(ne <n)
----------------------------------------------------------------------------------------------------------------------------------------------------
22
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
{
for(i = 1, min=999 ; i<= n ; i++)
{
for( j = 1 ; j <= n ; j++)
{
if(cost[i][j] < min)
{
a = i;
b = j;
min = cost[i][j];
}
}
}

if(min != I)
{
u = find(a);
v = find(b);
cost[a][b] =cost[b][a] = 999;

if(u != v)
{
System.out.println(ne++ +"edge("+a +" to" +b +") "+min);
mincost += min;
union(u,v);
}
}
}
System.out.println("Mincost="+mincost);
}

publicstaticvoid main(String[] args)


{
Kruskal k = newKruskal();
Scanner scan = newScanner(System.in);
inti, j, n;
int cost[][] = new int [10][10];
System.out.print("Enter the number of vertices in the Graph : ");
n = scan.nextInt();
System.out.println("Enter the cost adjacency matrix (enter 999 if no edge exists)");
for(i = 1 ; i<= n ; i++)
{
for(int j = 1 ; j <= n ; j++)
k.cost[i][j] = scan.nextInt();
if(cost[i][j] = 0)
k.cost[i][j] = 999;
}
System.out.println("Kruskalssolution”);
k.kruskal_soln(n);
}
}

----------------------------------------------------------------------------------------------------------------------------------------------------
23
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
Output.
Enter the number of vertices in the Graph : 4
Enter the weight matrix (enter 999 if no edge exists)
0 1 5 2
1 0 999 999
5 999 0 3
2 999 3 0

Kruskals solution
1 edge(1 to 2) 1
2 edge(1 to 4)2
3 edge(3 to 4)3

Mincost = 6

9.
Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's algorithm.
importjava.util.*;

public class Prims


{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
inti, j, n, u=0,v=0, ne=1, min=0, mincost=0;
System.out.print("Enter the number of vertices in the Graph : ");
n = scan.nextInt();
System.out.println("Enter the cost adjacency matrix (enter 999 if no edge exists)");
int cost[][] = new int[01][10];
int visited[] = new int[10];
for(i = 1 ; i<= n ; i++)
{
for( j = 1 ; j <= n ; j++)
cost[i][j] = scan.nextInt();
if(cost[i][j] = 0)
cost[i][j] = 999;
}
System.out.println("Prims solution”);
for(i = 1 ; i<= n ; i++)
visited[i]=0;
System.out.println("Edges of the spanning tree are:”);
visited[i]=0;
while(ne<1)
{
for(i = 1, min = 999 ; i<= n ; i++)
{
for( j = 1 ; j <= n ; j++)
{
if(cost[i][j]<min)
{
if(visited[i] == 0)
continue;
else
{
----------------------------------------------------------------------------------------------------------------------------------------------------
24
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
min = cost[i][j];
u=i, v=j;
}
}
}
}
if(visited[u] ==0 || visited[v] == 0);
{
System.out.println(ne++ +"edge("+u +" to" +v +") "+min);
mincost += min;
visited[v] = 1;
}
cost[u][v] = cost[v][u] = 999;
}
System.out.println("MinCost="+mincost);
}
}

Output.
Enter the number of vertices in the Graph : 4
Enter the weight matrix (enter 999 if no edge exists)
0 1 5 2
1 0 999 999
5 999 0 3
2 999 3 0

Prims solution
1 edge(1 to 2) 1
2 edge(1 to 4)2
3 edge(3 to 4)3

Mincost = 6

10a.
Write Java programs toImplement All-Pairs Shortest Paths problem using Floyd's algorithm.
importjava.util.Scanner;
publicclass Floyds
{
public static int main(int a, int b)
{
return((a<b)?a:b);
}
public static voidfloyds_soln(int a[][], int n)
{
inti,j,k;
for(k = 0 ; k < n ; k++)
for(i = 0 ; i<n ; i++)
for(j = 0 ; j <n; j++)
a[i][j] =min(a[i][j], a[i][k]+a[k][j]);
}

publicstaticvoid main(String args[])


{
----------------------------------------------------------------------------------------------------------------------------------------------------
25
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
inti,j, n;
Scanner scan = newScanner(System.in);
System.out.println("Enter the number of vertices");
n = scan.nextInt();
System.out.println("Enter the weight matrix (999 if no edge exists between vertices)");
int a[][] = new int[10][10];
for(i = 0 ; i< n ; i++)
{
for(j=0 ; j < n ; j++)
a[i][j] = scan.nextInt();
}
System.out.println("Floyds solution");
Floyds_soln(a,n);
System.out.println("Shortest path length matrix”);
for(i = 0 ; i< n ; i++)
{
for(j=0 ; j < n ; j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
}
}
Enter the number of vertices: 4
Enter the weight matrix (999 if no edge exists between vertices)
0 999 3 999
2 0 999 999
999 7 0 1
6 999 999 0

Floyds solution
Shortest path length matrix
0 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0

10b.
Write Java programs toImplement Travelling Sales Person problem using Dynamic programming.

importjava.util.*;

publicclass TSP
{
publicstaticvoid main(String args[])
{
int c[][] = new int[10][10], tour[] =new int[10];
Scanner scan = newScanner(System.in);
inti, j, n, cost;
System.out.print("TSP Dynamic Programming");
System.out.print("Enter the number of cities : ");
n = scan.nextInt();
if(n ==1)
{
----------------------------------------------------------------------------------------------------------------------------------------------------
26
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
System.out.println("Path is not possible");
System.exit(0);
}
System.out.println("Enter the cost matrix (enter 999 if no edge exists)");
edge = newint[vc][vc];
for(i = 1 ; i< n ; i++)
for( j =1 ; j <n ; j++)
c[i][j] = scan.nextInt();
for(i = 1 ; i< n ; i++)
tour[i] = i;
cost=tspdp(c, tour, 1, n);
System.out.println("Accurat path is");
for(i = 1 ; i< n ; i++)
System.out.println(tour[i]+ "");
System.out.println("1");
System.out.println("Accurate Mincost = " +cost);
}

publicinttspdp(int c[][] inttour,intstart, int n)


{
intmintour[] = new int[10], temp[] = new int[10], i, j, k, ccost, mincost = 999;

if(start == n - 1)
return c[tour[n-1]][tour[n]] + c[tour[n]][1];

for(i = start + 1 ; i<=n ; i++)


{
for(j = 1 ; j <=n ; j++)
temp[j] = tour[j];
temp[start+1] = tour[i];
temp[i] = tour[start+1];
if(c[tour[index]][tour[i]] + (ccost = tspdp(c,temp,start+1)) <mincost)
{
mincost = c[tour[start]][tour[i]] + ccost;
for(k = 1 ; k <=n ; k++)
mintour[k] = temp[k];
}
}
for(i = 1 ; i<=n ; i++)
tour[i] = mintour[i];
returnmincost;
}
}
Output.
TSP Dynamic Programming
Enter the number of cities : 4
Enter the cost matrix (enter 999 if no edge exists)
0 10 15 20
5 0 9 10
6 13 0 12
8 8 9 0
Accurate path is
0
Minimum cost = 35
----------------------------------------------------------------------------------------------------------------------------------------------------
27
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
12431
Accurate Mincost: 35

11.
Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n positive integers whose
SUM is equal to a given positive integer d. For example, if S ={1, 2, 5, 6, 8} and d= 9, there are two
solutions {1,2,6}and {1,8}. Display a suitable message, if the given problem instance doesn't have a
solution.
Import java.util.Scanner;
Public class SumofSubset {

public int d, n, count=0, i;


public int w[] = new int[10];
public int x[] = new int[10];

publicvoid subset(int s,int k,int r)


{
x[k] = 1;
if(s + w[k] == d)
{
System.out.println("Subset= "+ ++count);
for(i = 1 ; i<= k ; i++)
if(x[i] == 1)
System.out.print(" "+w[i]);
System.out.println();
}
elseifc<=d)
subset(s + w[k], k+1, r-w[k]);
if(s-r-w[k]>=d) && (s + w[k+1]<= d)
{
x[k] = 0;
subset(s + k+1, r-w[k]);
}
}

publicstaticvoid main(Stringargs[])
{
SumofSubset s = newSumofSubset();
inti, n, sum=0;

Scanner scan = newScanner(System.in);


System.out.print("Enter number of elements in a set : ");
n = scan.nextInt();
System.out.println("Enter the numbers in ascending order");
for(i = 1 ; i<= n ; i++)
s.w[i] = scan.nextInt();

System.out.println("Enter the sum value to create sub set");


s.d= scan.nextInt();
for(i = 1 ; i<= n ; i++)
{
s.x[i] = 0;
----------------------------------------------------------------------------------------------------------------------------------------------------
28
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
sum = sum+s.w[i];
}
if((sum<s.d) || (s.w[1]>s.d))
System.out.println("No subset possible");
else
s.subset(o, 1, sum);
}
}
Output.
Enter number of elements in a set : 4
Enter the numbers in ascending order: 1 3 6 7
Enter the sum value to create sub set
10
Subset= 1
136
Subset= 2
37

12.
Design and implement in Java to find all Hamiltonian Cycles in a connected undirected Graph G of n
vertices using backtracking principle.
importjava.util.Scanner;

public class Hamiltonian


{
publicint x[] = new int[25];
public void next_vertex(int G[], int n, int k)
{
int j;
boolean flag = true;
while(flag)
{
x[k] = (x[k] + 1) % (n +1);
if(x[k] ==0)
return;
if(G[x[k-1]][x[k]] != 0)
{
for(j =1 ; j <= k-1 ; j++)
{
if(x[j] == x[k])
break;
}
if(j == k)
{
if((k < n) || (k ==n) && (G[x[n]][x[1]] != 0 ))
return;
}
}
}
}
public void H_cycle(int g[], int n, int k)
{
inti;
boolean flag = true;
----------------------------------------------------------------------------------------------------------------------------------------------------
29
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
while(flag)
{
next_vertex(g, n, k);
if(x[k] == 0)
return;
if(k==n)
{
System.out.println("\n");
for(i =1 ; i<= n ; i++)
System.out.println(x[i] + "");
System.out.println("\t" + x[1]);
}
else
h_cycle(g, n, k+1);
}
}
public static void main(String[] args)
{
Hamiltonian ham = new Hamiltonian();
inti, j, v1, v2, n, edges;
int G[][] = new int[20][20];
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of vertices in a graph : ");
n = scan.nextInt();

for(i = 1 ; i<=n ; i++)


{
for( j = 1 ; j <=n ; j++)
{
G[i][j] = 0
ham.x[i] = 0;
}
}
System.out.println("Total no. of edges:");
edges = scan.nextInt();
for(i = 1 ; i<=edges ; i++)
{
System.out.println("Enter edges:");
v1 = scan.nextInt();
v2 = scan.nextInt();
G[v1][v2] = 1;
G[v2][v1] = 1;
}
ham.x[1] = 1;
System.out.println("Hamiltonian cycle");
ham.H_cycle(G, n, 2);
}
}

Output.
Enter the number of vertices in a graph : 5
Total no. of edges: 8
Enter edges: 1 2

----------------------------------------------------------------------------------------------------------------------------------------------------
30
The oxford college of Engineering ,Dept. of ISE DAA Lab Manual (18CSL47)
---------------------------------------------------------------------------------------------------------------------------------------------
Enter edges: 1 3
Enter edges: 1 6
Enter edges: 2 3
Enter edges: 2 6
Enter edges: 3 4
Enter edges: 4 5
Enter edges: 5 6

Hamiltonian cycle
1234561
1265431
1345621
1654321

----------------------------------------------------------------------------------------------------------------------------------------------------
31

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy