18csl47 - Daa Lab Manual
18csl47 - Daa Lab Manual
18csl47 - Daa Lab Manual
Prepared By
Deepthi N
Sushma Koushik N
Shashidhar S
Prasanna Patil
Divya H N
18CSL47 – DAA Lab IV-CSE
Descriptions
• Design, develop, and implement the specified algorithms for the following problems
using Java language under LINUX /Windows environment. Netbeans / Eclipse or
IntelliJ Idea Community Edition IDE tool can be used for development and
demonstration.
• Installation procedure of the required software must be demonstrated, carried out
in groups and documented in the journal.
The traditional procedural-languages separate the data structures (variables) and algorithms
(functions).
B. Object-oriented programming (OOP) languages are designed to overcome these
problems.
1. The basic unit of OOP is a class, which encapsulates both the static properties and dynamic
operations within a "box", and specifies the public interface for using these boxes. Since
classes are well encapsulated, it is easier to reuse these classes. In other words, OOP
combines the data structures and algorithms of a software entity inside the same box.
2. OOP languages permit higher level of abstraction for solving real-life problems. The
traditional procedural language (such as C and Pascal) forces you to think in terms of the
structure of the computer (e.g. memory bits and bytes, array, decision, loop) rather than
thinking in terms of the problem you are trying to solve. The OOP languages (such as Java,
C++ and C#) let you think in the problem
space, and use software objects to represent
and abstract entities of the problem space to
solve the problem.
C. Benefits of OOP
The procedural-oriented languages focus on
procedures, with function as the basic unit. You
need to first figure out all the functions and then
think about how to represent data.
The object-oriented languages focus on components that the user perceives, with objects as the
basic unit. You figure out all the objects by putting all the data and operations that describe the
user's interaction with the data.
➢ Data member represents either instance or static they will be selected based on the name of the class.
➢ User-defined methods represents either instance or static they are meant for performing the operations
either once or each and every time.
➢ Each and every java program starts execution from the main() method. And hence main() method is
known as program driver.
➢ Since main() method of java is not returning any value and hence its return type must be void.
➢ Since main() method of java executes only once throughout the java program execution and hence its
nature must be static.
➢ Since main() method must be accessed by every java programmer and hence whose access specifier
must be public.
➢ Each and every main() method of java must take array of objects of String.
➢ block of statements represents set of executable statements which are in term calling user-defined
methods are containing business-logic.
➢ The file naming conversion in the java programming is that which-ever class is containing main()
method, that class name must be given as a file name with an extension .java.
Compile and Run Java Program
Steps For compile Java Program:
➢ First Save Java program with same as class name with .java extension.
Example: Sum.java
Compile: javac Filename.java
Example, javac Sum.java
Note: Here javac is tools or application programs or exe files which is used for Compile the Java
program.
Steps For Run Java Program:
✓ For run java program use java tool.
✓ Run bY: java Filename
Example: java sum
Note: Here java is tools or application programs or exe files which is used for run the Java program.
Syllabus
1.
a. Create a Java class called Student with the following details as variables within it.
1. USN
2. Name
3.Branch
4.Phone
Write a Java program to create nStudent objects and print the USN, Name, Branch,
and Phone of these objects with suitable headings.
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 <name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> 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
18CSL47 – DAA Lab IV-CSE
computes the square of the number and prints third thread will print the value of
cube of the number.
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 divide-and-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) Greedy method.
7. From a given vertex in a weighted connected graph, find shortest paths to other vertices
using Dijkstra'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. Implement Travelling Sales Person problem using Dynamic programming.
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.
18CSL47 – DAA Lab IV-CSE
Program 1
import java.util.Scanner;
class stdinfo
{
Scanner in=new Scanner(System.in);
String usn=new String();
String name=new String();
String branch=new String();
int ph;
public void read()
{
System.out.println("Enter USN,Name,Branch,Phone no.");
usn=in.next();
name=in.next();
branch=in.next();
ph=in.nextInt();
}
public void prt()
{
System.out.print(usn+"\t"+name+"\t"+branch+"\t"+ph+"\n");
}
}
class student
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of students");
int n=in.nextInt();
stdinfo[] ob=new stdinfo[n];
System.out.println("Enter the details of the
students");
for(int i=0;i<n;i++)
{ System.out.println("Student:"+(i+1));
ob[i]=new stdinfo();
ob[i].read();
}
System.out.println("Student List is:");
System.out.print("USN\tName\tBranch\tPhone no"\n");
for(int i=0;i<n;i++)
18CSL47 – DAA Lab IV-CSE
ob[i].prt();
}
}
_____________________________________________________
Output
javac student.java
java student
int op=in.nextInt();
switch(op)
{
case 1: System.out.println("Enter element");
int x= in.nextInt();
ob.push(x);
break;
case 2: ob.pop();
break;
case 3: ob.dis();
break;
case 4: flag=0;
break;
default:System.out.println("Invalid Option");
}
}
}
}
Output
javac stack.java
java stk
Enter
1.Push
2.Pop
3.Display
4.Exit
Enter Your Option
1
Enter element
1
Enter Your Option
1
Enter element
2
Enter Your Option
1
Enter element
3
Enter Your Option
1
Enter element
4
Overflow
Enter Your Option
3
1 2 3
Enter Your Option
2
Deleted Element is 3
Enter Your Option
18CSL47 – DAA Lab IV-CSE
2
Deleted Element is 2
Enter Your Option
2
Deleted Element is 1
Enter Your Option
2
Underflow
Enter Your Option
3
Stack empty
Enter Your Option
4
Program 2
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 atleast 3 staffs in each category.
import java.util.*;
class staff
{
String stid=new String();
String stname=new String();
String stph=new String();
String stsal=new String();
Scanner in= new Scanner(System.in);
public void read()
{
System.out.println("Enter Staff Details(Staff ID,Name,Phone
no.and Salary)");
stid=in.nextLine();
stname=in.nextLine();
stph=in.nextLine();
stsal=in.nextLine();
}
public void display()
{
System.out.println("Staff
ID:"+stid+"\nName:"+stname+"\nPhone:"+stph+"\nSalary:"+stsal);
}
}
class teaching extends staff
{
static String tdom=new String();
static String tpbl=new String();
public void tread()
{
super.read();
18CSL47 – DAA Lab IV-CSE
Output
Enter no. of staffs
3
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
1
Adam
345678
12000
Enter Teaching Details(Domain and Publications)
ML
IEEE
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
2
Brad
234566
18CSL47 – DAA Lab IV-CSE
12000
Enter Teaching Details(Domain and Publications)
IOT
IEEE
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
3
Calvin
345678
12000
Enter Teaching Details(Domain and Publications)
AI
IEEE
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
4
David
567867
12000
Enter Technical Details(Skills)
Testing
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
5
Eris
678567
12000
Enter Technical Details(Skills)
Programming in JAVA
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
6
Fushia
345456
12000
Enter Technical Details(Skills)
ARM
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
7
Greg
765765
6000
Enter Contract Details(Period in years)
5
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
8
Hughes
987876
6000
Enter Contract Details(Period in years)
4
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
9
Jack
323243
18CSL47 – DAA Lab IV-CSE
6000
Enter Contract Details(Period in years)
4
Teaching Staff Details:
Staff ID:1
Name:Adam
Phone:345678
Salary:12000
Teaching Details:
Domain:ML
Publications:IEEE
Staff Details:
Staff ID:2
Name:Brad
Phone:234566
Salary:12000
Teaching Details:
Domain:IOT
Publications:IEEE
Staff Details:
Staff ID:3
Name:Calvin
Phone:345678
Salary:12000
Teaching Details:
Domain:AI
Publications:IEEE
Technical Staff Details:
Staff ID:4
Name:David
Phone:567867
Salary:12000
Technical Details:
Skills:Testing
Staff ID:5
Name:Eris
Phone:678567
Salary:12000
Technical Details:
Skills:ARM
Staff ID:6
Name:Fushia
Phone:345456
Salary:12000
Technical Details:
Skills:ARM
Contract Staff Details:
Staff ID:7
Name:Greg
Phone:765765
Salary:6000
18CSL47 – DAA Lab IV-CSE
Contract Details:
Period:4years
Staff ID:8
Name:Hughes
Phone:987876
Salary:6000
Contract Details:
Period:4years
Staff ID:9
Name:Jack
Phone:323243
Salary:6000
Contract Details:
Period:4years
class Exp
{
public static void main(String par[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the value of a,b");
int a=in.nextInt();
int b=in.nextInt();
try {
int result=a/b;
System.out.println("Result = "+result);
}
catch(Exception e) {
System.out.println("Exception caught : "+e);
}
}
}
Output
1) No Exception
Enter the value of a,b
2 1
Result = 2
2) Divide by Zero
Enter the value of a,b
1 0
Exception caught : java.lang.ArithmeticException: / by
zero
______________________________________________________________
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 and prints third thread will print the
value of cube of the number.
import java.util.*;
class Firstthread extends Thread
{
Firstthread()
{
start();
}
public void run()
{
try
{
for(int i=0;i<3;i++)
{
Random r=new Random();
int n=r.nextInt(100);
System.out.println("Number = "+n);
new Secondthread(n);
new Thirdthread(n);
18CSL47 – DAA Lab IV-CSE
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println("First thread interrupted");
}
System.out.println("First thread exiting");
}
}
class Secondthread extends Thread
{
int x;
Secondthread(int n)
{
x=n;
start();
}
public void run()
{
try
{
System.out.println(" Square = " +(x*x));
}
catch(Exception e)
{
System.out.println("Second thread interrupted");
}
System.out.println("Second thread exiting");
}
}
class Thirdthread extends Thread
{
int x;
Thirdthread(int n)
{
x=n;
start();
}
public void run()
{
try
{
System.out.println("Cube = " +(x*x*x));
}
catch(Exception e)
{
System.out.println("Third thread interrupted");
}
System.out.println("Third thread exiting");
}
18CSL47 – DAA Lab IV-CSE
}
class Mainthread
{
public static void main(String args[])
{
new Firstthread();
}
}
Output
Number = 82
Square = 6724
Second thread exiting
Cube = 551368
Third thread exiting
Number = 32
Square = 1024
Second thread exiting
Cube = 32768
Third thread exiting
Number = 66
Square = 4356
Second thread exiting
Cube = 287496
Third thread exiting
First thread exiting
Program 4
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.
import java.util.Random;
import java.util.Scanner;
class Quick
{
static int a[]=new int[10000];
static Random r=new Random();
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of elements");
int n=in.nextInt();
for(int k=0;k<n;k++)
{
a[k]=5000+r.nextInt(999);
}
System.out.println("Before Quicksort");
for(int m=0;m<n;m++)
18CSL47 – DAA Lab IV-CSE
{
System.out.print(a[m]+" ");
}
System.out.print("\n");
System.out.println("After Quicksort");
long startTime=System.nanoTime();
Qsort(a,0,n-1);
long stopTime=System.nanoTime();
long eTime=stopTime-startTime;
for(int h=0;h<n;h++)
{
System.out.print(a[h]+" ");
}
System.out.print("\n");
System.out.println("Elapsed time ="+eTime);
}
public static int part(int a[],int low,int high)
{
int j=low;
int pv=high;
int i=j-1;
int temp;
while(j<=pv)
{
while(a[j]<a[pv])
j++;
while(a[j]>a[pv])
{
i++;
temp=a[i];
a[i]=a[j];
a[j]=temp;
j++;
}
if(a[j]==a[pv])
{
i++;
temp=a[i];
a[i]=a[j];
a[j]=temp;
j++;
}
}
return i;
}
public static void Qsort(int a[],int low,int high)
{
if(low<=high)
{
int mid=part(a,low,high);
Qsort(a,0,mid-1);
18CSL47 – DAA Lab IV-CSE
Qsort(a,mid+1,high);
}
}
}
Output
Enter the number of elements
5
Before Quicksort
5263 5535 5979 5391 5620
After Quicksort
5979 5620 5535 5391 5263
Elapsed time =46896
Graph
______________________________________________________________
Program 5
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 divide-and-conquer
method works along with its time complexity analysis: worst
case, average case and best case.
import java.util.*;
class merge
{
static int a[]=new int[10000];
static Random r=new Random();
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of elements");
int n=in.nextInt();
for(int k=0;k<n;k++)
{
18CSL47 – DAA Lab IV-CSE
a[k]=r.nextInt(999);
}
System.out.println("Before Mergesort");
for(int m=0;m<n;m++)
{
System.out.print(a[m]+" ");
}
System.out.print("\n");
System.out.println("After Mergesort");
long startTime=System.nanoTime();
mergesort(a,0,n-1);
long stopTime=System.nanoTime();
long eTime=stopTime-startTime;
for(int h=0;h<n;h++)
{
System.out.print(a[h]+" ");
}
System.out.print("\n");
System.out.println("Elapsed time
="+(eTime/1000000)+”ms”);
}
public static void mergesort(int a[],int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,high,mid);
}
}
public static void merge(int a[],int low,int high,int mid)
{
int i=low,j=mid+1,k=low;
int b[]=new int[10000];
while(i<=mid&&j<=high)
{
if(a[i]<a[j])
{
b[k]=a[i];
k++;i++;
}
else
{
b[k]=a[j];
k++;j++;
}
}
while(i<=mid)
{
b[k]=a[i];
18CSL47 – DAA Lab IV-CSE
k++;i++;
}
while(j<=high)
{
b[k]=a[j];
k++;j++;
}
for(i=low;i<=high;i++)
{
a[i]=b[i];
}
}
}
Output
Enter the number of elements
5
Before Mergesort
754 16 631 566 326
After Mergesort
16 326 566 631 754
Elapsed time =0 ms
Graph
______________________________________________________________
Program 6
6) Implement in Java, the 0/1 Knapsack problem using (a) Dynamic
Programming method (b) Greedy method.
(a)
import java.util.Scanner;
class KnapsackDP
{
static int wt[]=new int[10];
static int pr[]=new int[10];
public static int knapsack(int n,int m)
18CSL47 – DAA Lab IV-CSE
{
if(n==0||m==0)
return 0;
else if(wt[n]>m)
return knapsack(n-1,m);
else
return max(pr[n]+knapsack(n-1,m-wt[n]),knapsack(n-1,m));
}
public static int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter number of objects");
int n=in.nextInt();
System.out.println("Enter profit array");
for(int i=1;i<=n;i++)
pr[i]=in.nextInt();
System.out.println("Enter weight array");
for(int i=1;i<=n;i++)
wt[i]=in.nextInt();
System.out.println("Enter maximum weight");
int m=in.nextInt();
int maxpro=knapsack(n,m);
System.out.println("Maximum Profit = "+maxpro);
}
}
Output
Enter number of objects
5
Enter profit array
10 23 14 32 15
Enter weight array
2 3 1 4 1
Enter maximum weight
5
Maximum Profit = 52
(b)
import java.util.Scanner;
class KnapsackGreedy
{
static int wt[]=new int[10];
static float wp[]=new float[10];
static float twp[]=new float[10];
static int pr[]=new int[10];
static int n,curwt=0,remwt;
18CSL47 – DAA Lab IV-CSE
}
}
Output
Enter number of objects
4
Enter profit array
40 42 25 12
Enter weight array
4 7 5 3
Enter maximum weight
10
Maximum Profit = 76.0
Program 7
7) From a given vertex in a weighted connected graph, find
shortest paths to other vertices using Dijkstra's algorithm.
Write the program in Java.
import java.util.Scanner;
class Djk
{
static int n;
static int v[]=new int[10];
static int d[]=new int[10];
static int a[][]=new int[10][10];
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of nodes");
n=in.nextInt();
System.out.println("Enter the cost matrix");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
a[i][j]=in.nextInt();
System.out.println("Enter source node");
int src=in.nextInt();
dk(src);
for(int j=1;j<=n;j++)
{
if(j!=src)
System.out.println("Cost from "+src+" to "+j+" is
"+d[j]);
}
}
public static void dk(int src)
{
for(int i=1;i<=n;i++)
{
v[i]=0;
d[i]=a[src][i];
}
v[src]=1;
int x=2,m;
18CSL47 – DAA Lab IV-CSE
while(x<=n)
{
m=min();
v[m]=1;
for(int j=1;j<=n;j++)
{
if((d[m]+a[m][j]<d[j])&&(v[j]==0)&&v[j]==0&&m!=-1)
d[j]=d[m]+a[m][j];
}
x++;
}
}
public static int min()
{
int min=999,j=-1;
for(int i=1;i<=n;i++)
if(d[i]<min&&v[i]==0)
{
min=d[i];
j=i;
}
return j;
}
}
Output
Enter the number of nodes
5
Enter the cost matrix
999 3 999 7 999
3 999 4 2 999
999 4 999 5 6
7 2 5 999 4
999 999 6 4 999
Enter source node
1
Cost from 1 to 2 is 3
Cost from 1 to 3 is 7
Cost from 1 to 4 is 5
Cost from 1 to 5 is 9
Program 8
8) Find Minimum Cost Spanning Tree of a given connected
undirected graph using Kruskal's algorithm. Use Union-Find
algorithms in your program.
import java.util.Scanner;
class Krusk
{
static int n,ne=1,min=999,mincost=0;
static int parent[]=new int[11];
static int cost[][]=new int[10][10];
public static void main(String args[])
{
18CSL47 – DAA Lab IV-CSE
{
while(parent[i]!=0)
i=parent[i];
return i;
}
}
Output
Enter the number of nodes
4
Enter the cost matrix
999 4 1 1
4 999 999 3
1 999 999 2
1 3 2 999
Edge 1 to 3 with cost 1
Edge 1 to 4 with cost 1
Edge 2 to 4 with cost 3
Total cost is = 5
Program 9
9) Find Minimum Cost Spanning Tree of a given connected
undirected graph using Prim's algorithm.
import java.util.Scanner;
class Prim
{
static int n,ne=1,min=999,mincost=0;
static int visited[]=new int[11];
static int cost[][]=new int[10][10];
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of nodes");
n=in.nextInt();
System.out.println("Enter the cost matrix");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cost[i][j]=in.nextInt();
prim(cost);
}
{
min=cost[i][j];
u=i;
v=j;
}
}
}
if(visited[u]==0||visited[v]==0)
{
System.out.println("Edge "+u+" to "+v+" with cost
"+cost[u][v]);
mincost=mincost+cost[u][v];
visited[v]=1;
ne++;
}
cost[u][v]=cost[v][u]=999;
}
System.out.println("Total cost is = "+mincost);
}
}
Output
Enter the number of nodes
4
Enter the cost matrix
999 4 1 1
4 999 999 3
1 999 999 2
1 3 2 999
Edge 1 to 3 with cost 1
Edge 1 to 4 with cost 1
Edge 2 to 4 with cost 3
Total cost is = 5
Program 10
10) Write Java programs to
a. Implement All-Pairs Shortest Paths problem using Floyd's
algorithm.
b. Implement Travelling Sales Person problem using Dynamic
programming.
______________________________________________________________
a)
import java.util.Scanner;
class Floyd
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int cost[][]=new int[10][10];
System.out.println("Enter the number of nodes");
int n=in.nextInt();
System.out.println("Enter the cost matrix");
for(int i=0;i<n;i++)
18CSL47 – DAA Lab IV-CSE
for(int j=0;j<n;j++)
cost[i][j]=in.nextInt();
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<n;k++)
if(cost[j][k]>cost[j][i]+cost[i][k])
cost[j][k]=cost[j][i]+cost[i][k];
System.out.println("Matrix is ");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(cost[i][j]+" ");
System.out.println();
}
}
}
Output
Enter the number of nodes
4
Enter the cost matrix
0 3 4 999
2 0 999 10
999 999 0 5
2 3 999 0
Matrix is
0 3 4 9
2 0 6 10
7 8 0 5
2 3 6 0
b)
import java.util.*;
class TSPDP
{
static int MAX=10;
static final int infinity=99;
static Scanner in=new Scanner(System.in);
public static void main(String args[])
{
int cst=infinity;
int cost[][]=new int[MAX][MAX];
int tour[]=new int[MAX];
int n;
System.out.println("Enter the number of Cities");
n=in.nextInt();
System.out.println("Enter the cost matrix");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cost[i][j]=in.nextInt();
for(int i=0;i<n;i++)
tour[i]=i;
cst=tspdp(cost,tour,0,n);
18CSL47 – DAA Lab IV-CSE
System.out.println("Cost is "+cst);
System.out.println("Tour : ");
for(int i=0;i<n;i++)
System.out.print((tour[i]+1)+ "->");
System.out.println(tour[0]+1);
in.close();
}
public static int tspdp(int cost[][],int tour[],int
start,int n)
{
int i,j,k;
int tmp[]=new int[MAX];
int mintour[]=new int[MAX];
int mincost;
int cst;
if(start==n-2)
return cost[tour[n-2]][tour[n-1]]+cost[tour[n-1]][0];
mincost=999;
for(i=start+1;i<n;i++)
{
for(j=0;j<n;j++)
tmp[j]=tour[j];
tmp[start+1]=tour[i];
tmp[i]=tour[start+1];
if(((cost[tour[start]][tour[i]])+(cst=tspdp(cost,tmp,start+1,n
)))<mincost)
{
mincost=(cost[tour[start]][tour[i]])+cst;
for(k=0;k<n;k++)
mintour[k]=tmp[k];
}
}
for(i=0;i<n;i++)
tour[i]=mintour[i];
return mincost;
}
}
Output
Enter the number of Cities
5
Enter the cost matrix
0 7 6 8 4
7 0 8 5 6
6 8 0 9 7
8 5 9 0 8
4 6 7 8 0
Cost is 30
Tour :
1->3->4->2->5->1
18CSL47 – DAA Lab IV-CSE
Program 11
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;
class subset
{
public static int set[]=new int[1000];
public static int sol[]=new int[1000];
public static int sum=0,flag=0,n;
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of elements in the
set");
n=in.nextInt();
System.out.println("Enter the set ");
for(int i=0;i<n;i++)
set[i]=in.nextInt();
System.out.println("Enter the sum value ");
sum=in.nextInt();
System.out.println("The Subsets are ");
subset(set,sol,sum,0,0);
if(flag==0)
System.out.println("No Subsets found");
}
public static void subset(int set[],int sol[],int sum,int
cursum,int index)
{
if(cursum==sum)
{
for(index=0;index<n;index++)
if(sol[index]==1)
System.out.print(set[index]+" ");
System.out.println();
flag=1;
}
if(index==n)
return;
else
{
sol[index]=1;
cursum+=set[index];
subset(set,sol,sum,cursum,index+1);
sol[index]=0;
cursum-=set[index];
subset(set,sol,sum,cursum,index+1);
}
18CSL47 – DAA Lab IV-CSE
}
}
Output
Enter the number of elements in the set
5
Enter the set
1 2 5 6 8
Enter the sum value
9
The Subsets are
1 2 6
1 8
Enter the number of elements in the set
2
Enter the set
1 2
Enter the sum value
5
The Subsets are
No Subsets found
Program 12
12) Design and implement in Java to find all Hamiltonian Cycles
in a connected undirected Graph G of n vertices using
backtracking principle.
import java.util.*;
class HamiltonianCycle
{
private int adj[][],x[],n;
public HamiltonianCycle()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of nodes");
n=in.nextInt();
x=new int[n];
x[0]=0;
for (int i=1;i<n; i++)
x[i]=-1;
adj=new int[n][n];
System.out.println("Enter the adjacency matrix");
for (int i=0;i<n; i++)
for (int j=0; j<n; j++)
adj[i][j]=in.nextInt();
}
if(x[k]==n)
{
x[k]=-1;
return;
}
if (adj[x[k-1]][x[k]]==1)
for (i=0; i<k; i++)
if (x[i]==x[k])
break;
if (i==k)
if (k<n-1||k==n-1&&adj[x[n-1]][0]==1)
return;
}
}
public void getHCycle(int k)
{
while(true)
{
nextValue(k);
if (x[k]==-1)
return;
if (k==n-1)
{
System.out.println("\nSolution : ");
for (int i=0; i<n; i++)
System.out.print((x[i]+1)+" ");
System.out.println(1);
}
else getHCycle(k+1);
}
}
}
class Hamiltonian
{
public static void main(String args[])
{
HamiltonianCycle obj=new HamiltonianCycle();
obj.getHCycle(1);
}
}
Output
5
Enter the adjacency matrix
0 1 0 1 0
1 0 1 1 1
0 1 0 0 1
1 1 0 0 1
0 1 1 1 0
18CSL47 – DAA Lab IV-CSE
Solution :
1 2 3 5 4 1
Solution :
1 4 5 3 2 1
(1)--(2)--(3)
| / \ |
| / \ |
| / \ |
(4)-------(5)
18CSL47 – DAA Lab IV-CSE