n2bgw Ig8ps

You might also like

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

DESIGN AND ANALYSIS OF ALGORITHM LABORATORY

[As per Choice Based Credit System (CBCS)


scheme] (Effective from the academic year 2016
-2017)
Subject Code 15CSL47 IA Marks 20
Number of Lecture Hours/Week 01 I + 02 P Exam Marks 80
Total Number of Lecture Hours 40 Exam Hours 03
CREDITS – 02
Course objectives: This course will enable students to
 Design and implement various algorithms in JAVA
 Employ various design strategies for problem solving.
 Measure and compare the performance of different algorithms.
Description
Design, develop, and implement the specified algorithms for the following problems using
Java language under LINUX /Windows environment.Netbeans/Eclipse IDE tool can be used
for development and demonstration.
Experiments
1 Create a Java class called Studentwith the following details as variables within it.
(i) USN
A
(ii) Name
(iii) Branch
(iv) Phone

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
computes the square of the number andprints; 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.

1 Write Java programs to


0 (a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
(b) Implement Travelling Sales Person problem using Dynamic programming.
1 Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n
1 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.

1 Design and implement in Java to find all Hamiltonian Cycles in a connected


2 undirected Graph G of n vertices using backtracking principle.
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.
import java.util.Scanner;

public class Student


{
public String usn;
public String name;
public String branch;
public long phone;

public void readStudentDetails(int i)


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

public void displayStudentDetails()


{
System.out.format("%-15s%-15s%-15s%-15s\n",usn,name,branch,phone);
}
public static void main(String[] args)
{
System.out.println("Enter number of students : ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
Student stud[] = new Student[num];
for(int i = 0 ; i < num ; i++)
{
stud[i] = new Student();
stud[i].readStudentDetails(i);
}
System.out.println("-------------------------------------------------------------
--------");
System.out.format("%-15s%-15s%-15s%-15s\n", "USN" ,"Name" , "Branch",
"Phone No.");
System.out.println("------------------------------------------------------------------");
for(int i = 0 ; i < num ; i++)
{
stud[i].displayStudentDetails();
}
}
}
Output :

1b.
Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods to
demonstrate its working.
import java.util.Scanner;
public class StackClass {
private int stack[];
private int tos=-1;
private int maxnumber;
public void push()
{
if(tos==maxnumber-1)
{
System.out.println("Stack Overflow");
return;
}
else
{
tos++;
System.out.println("Enter element to be pushed");
Scanner scan=new Scanner(System.in);
int element=scan.nextInt();
stack[tos]=element;
System.out.println("Element is pushed");
}
}
public void pop()
{
if(tos==-1)
{
System.out.println("Stack underflow");
return;
}
System.out.println("popped element is "+stack[tos]);
tos--;
}
public void display()
{
int count=tos;
if(count == -1)
System.out.println("Stack is empty");
for(int i=count;i>=0;i--)
{
System.out.println(stack[i]);
}
}
public static void main(String args[])
{
System.out.println("Enter stack size");
Scanner scan=new Scanner(System.in);
int size=scan.nextInt();
StackClass sc=new StackClass();
sc.maxnumber=size;
sc.stack=new int[size];
while(true)
{
System.out.println("Enter 1 to push 2 to pop 3 to display 4 to exit");
int option=scan.nextInt();
switch(option)
{
case 1:
sc.push();
break;
case 2:
sc.pop();
break;
case 3:
sc.display();
break;
case 4:
System.exit(0);

}
}
}
}
Output

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.

//staff class
import java.util.Scanner;

public class Staff {

Scanner scan = new Scanner( System.in );


int StaffId,Phone, Salary;
String Name;
void read_staff_details()
{
System.out.println("Enter Staff name");
Name = scan.next();
System.out.println("Enter Staffid");
StaffId = scan.nextInt();
System.out.println("Enter Phone no.");
Phone = scan.nextInt();
System.out.println("Salary");
Salary= scan.nextInt();
}

void display_staff_details()
{
System.out.print(Name+"\t"+StaffId+"\t"+Phone+"\t"+Salary+"\t");

//Teaching class
public class Teaching extends Staff{
String domain;
int no_publication;
void read_domain_publication()
{
System.out.println("Enter domain");
domain = scan.next();
System.out.println("Enter number of publications");
no_publication = scan.nextInt();
}

void display_domain_publication()
{
System.out.print(domain+"\t"+no_publication);
System.out.println("\n");
}

//Technical class

public class Technical extends Staff{


String skills;
void read_skills()
{
System.out.println("Enter skills");
skills = scan.next();
}
void display_skills()
{
System.out.print(skills);
System.out.println("\n");
}
}
//Contract class

public class Contract extends Staff{

int period;
void read_contract_period()
{
System.out.println("Enter contract period");
period = scan.nextInt();
}
void display_contract_period()
{
System.out.print(period);
System.out.println("\n");
}
}
//Staffmain class
import java.util.Scanner;

public class Staffmain {

public static void main(String[] args) {


Scanner scan = new Scanner( System.in );
System.out.println("how many number of Teaching Staff details do you wish to
enter\n ");
int n = scan.nextInt();
Teaching[] teach = new Teaching[n];
System.out.println("how many number of Technical Staff details do you wish to
enter\n ");
int t = scan.nextInt();
Technical[] tech = new Technical[t];
System.out.println("how many number of contract Staff details do you wish to
enter\n ");
int c = scan.nextInt();
Contract[] cont = new Contract[c];

for(int i = 0 ; i<n ; i++)


{
System.out.println("Enter "+(i+1)+" Teaching Staff details\n ");
teach[i]= new Teaching();
teach[i].read_staff_details();
teach[i].read_domain_publication();
}
for(int i = 0 ; i<t ; i++)
{
System.out.println("Enter "+(i+1)+" Technical Staff details\n ");
tech[i] = new Technical();
tech[i].read_staff_details();
tech[i].read_skills();
}

for(int i = 0 ; i<c ; i++)


{
System.out.println("Enter "+(i+1)+" contract Staff details\n ");
cont[i] = new Contract();
cont[i].read_staff_details();
cont[i].read_contract_period();
}
System.out.println("Teaching staff details are\n");
System.out.println("---------------------------------------------------------");

System.out.println("Name\t"+"St_id\t"+"ph_no\t"+"salary\t"+"domain\t"+"no_publication\
n");
System.out.println("---------------------------------------------------------");

for(int i = 0 ; i<n ; i++)


{
teach[i].display_staff_details();
teach[i].display_domain_publication();
}

System.out.println("---------------------------------------------------------\n\n");

System.out.println("Technical staff details are\n");


System.out.println("---------------------------------------------------------");
System.out.println("Name\t"+"St_id\t"+"ph_no\t"+"salary\t"+"skills\n");
System.out.println("---------------------------------------------------------");

for(int i = 0 ; i<t ; i++)


{
tech[i].display_staff_details();
tech[i].display_skills();
}

System.out.println("---------------------------------------------------------\n\n");

System.out.println("contract staff details are\n");


System.out.println("---------------------------------------------------------");
System.out.println("Name\t"+"St_id\t"+"ph_no\t"+"salary\t"+"contract period\n");
System.out.println("---------------------------------------------------------");
for(int i = 0 ; i<n ; i++)
{
cont[i].display_staff_details();
cont[i].display_contract_period();
}

System.out.println("---------------------------------------------------------\n");
}
}

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
<name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using StringTokenizer class considering the
delimiter character as “/”.
import java.util.Scanner;
import java.util.StringTokenizer;
public class Customer {

String name,DOB;
Scanner scan = new Scanner( System.in );
void read_name_DOB()
{

System.out.println("Enter name of the customer");


name = scan.next();
System.out.println("Enter DOB of the customer in the format dd/mm/yy");
DOB = scan.next();

void display_name_DOB()
{
StringTokenizer st = new StringTokenizer(DOB,"/");
//System.out.println("name of the customer-------->"+name);
String dd = st.nextToken();
String mm = st.nextToken();
String yy = st.nextToken();
System.out.println("<"+name+" ,"+dd+","+mm+","+yy+">");
}

public static void main(String[] args)


{
Customer c = new Customer();
c.read_name_DOB();
c.display_name_DOB();
}
}

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.
public class Exception2a {
public static void main(String[] args) {
Scanner scan = new Scanner( System.in );
int a = 0,b=0,result=0;

System.out.println("Enter 'a' value");


a = scan.nextInt();

System.out.println("Enter 'b' value");


b = scan.nextInt();

try {

int c = a / b;
result = c;
System.out.println("The result: "+result);
} catch(ArithmeticException ex) {
System.out.println("since b=0 thier is divide by zero exception");
}

}
}

OUTPUT1:
Enter 'a' value
4
Enter 'b' value
0
since b=0 thier is divide by zero exception

OUTPUT 2:
Enter 'a' value
4
Enter 'b' value
6
The result: 0

3.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.
//class for square print
public class SquarePrint implements Runnable
{
public int x;
public SquarePrint(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread Square of " + x + " is: " + x * x);
}

//class for cube print


public class CubePrint implements Runnable{
public int x;
public CubePrint(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread calculating and printing>>>>> Cube of " + x + "
is: " + x * x * x);
}

}
//class for 3 threads
import java.util.*;

public class A extends Thread {


public void run()
{
int num = 0;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
Thread t1 = new Thread(new SquarePrint(num));
t1.start();

Thread t2 = new Thread(new CubePrint(num));


t2.start();

Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}

}
//main class
public class Threads_3b {
public static void main(String[] args)
{
A a = new A();
a.start();
}

OUTPUT:
Main Thread and Generated Number is 45
New Thread Square of 45 is: 2025
New Thread calculating and printing>>>>> Cube of 45 is: 91125
--------------------------------------
Main Thread and Generated Number is 25
New Thread Square of 25 is: 625
New Thread calculating and printing>>>>> Cube of 25 is: 15625
--------------------------------------
Main Thread and Generated Number is 71
New Thread Square of 71 is: 5041
New Thread calculating and printing>>>>> Cube of 71 is: 357911
--------------------------------------
Main Thread and Generated Number is 82
New Thread Square of 82 is: 6724
New Thread calculating and printing>>>>> Cube of 82 is: 551368
--------------------------------------
Main Thread and Generated Number is 68
New Thread Square of 68 is: 4624
New Thread calculating and printing>>>>> Cube of 68 is: 314432
--------------------------------------
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.*;

/* Class QuickSort */
public class QuickSort
{
/* Quick Sort function */
public static int partition(int low,int high,int a[])
{
int i,j,key,temp;
i=low;
j=high+1;
key=a[low]; //assigning the first value in array as key.
while(i<=j)
{ do i++;
while(i<=high && key>=a[i]);
do j--;
while(j>=low && key<a[j]);

if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;
}
public static void quick_sort(int low,int high,int a[])
{
int mid;
if(low<high)
{
mid=partition(low,high,a);
quick_sort(low,mid-1,a);//Call recursively to sort the left
part
quick_sort(mid+1,high,a); //Call recursively to sort the right
part

}
}

/* Main method */
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
Random ran = new Random();
System.out.println("Quick Sort Test\n");
int n, i;
/* Accept number of elements */
System.out.println("Enter number of integer elements");
n = scan.nextInt();
/* Create array of n elements */
int a[] = new int[n];
/* Accept elements */
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
a[i] = ran.nextInt(n);
for (i = 0; i < n; i++)
System.out.print(a[i]+" ");
long start = System.nanoTime ();
/* Call method sort */
quick_sort( 0, n-1,a);
long end= System.nanoTime();
/* Print sorted Array */
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(a[i]+" ");
System.out.println();
double total=end-start;
System.out.println (total/1000000000);
}
}

OUTPUT:
Quick Sort Test

Enter number of integer elements


30

Enter 30 integer elements


2 3 25 18 19 5 13 1 5 26 25 10 0 18 7 6 25 7 9 26 3 17 16 23 5 7 7 8 4 2
Elements after sorting
0 1 2 2 3 3 4 5 5 5 6 7 7 7 7 8 9 10 13 16 17 18 18 19 23 25 25 25 26 26
2.1189E-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.

* Java Program to Implement Merge Sort

*/

import java.utl.**
/* Class MergeSort */

public class MergeSort

/* Merge Sort functon */

public statc voii simple_merge(int[] a, int low,int mii, int high)

// merge two sortei subarrays

int[] b = new int[1000]*

int i=low, j=mii+1, k=low*

while ( i<=mii && j<=high )

if( a[i] <= a[j] )

b[k++] = a[i++] *

else

b[k++] = a[j++] *

while (i<=mii)

b[k++] = a[i++] *

while (j<=high)

b[k++] = a[j++] *

for(k=low* k<=high* k++)

a[k] = b[k]*

public statc voii sort(int[] a,int low,int high)

if (low>=high)

return*

int mii = (low + high)/2*

// recursively sort

sort(a, low, mii)*


sort(a, mii+1, high)*

simple_merge(a,low,mii,high)*

/* Main methoi */

public statc voii main(String[] args)

Scanner scan = new Scanner( System.in )*

Raniom ran = new Raniom()*

System.out.println("Merge Sort Test\n")*

int n, i*

/* Accept number of elements */

System.out.println("Enter number of integer elements")*

n = scan.nextInt()*

/* Create array of n elements */

int a[] = new int[ n ]*

/* Accept elements */

System.out.println("\nEnter "+ n +" integer elements")*

for (i = 0* i < n* i++)

a[i] = ran.nextInt(n)*

for (i = 0* i < n* i++)

System.out.print(a[i]+" ")*

long start = System.nanoTime ()*

/* Call methoi sort */

sort(a, 0, n-1)*

long eni= System.nanoTime()*

/* Print sortei Array */

System.out.println("\nElements afer sortng ")*

for (i = 0* i < n* i++)

System.out.print(a[i]+" ")*
System.out.println()*

iouble total=eni-start*

System.out.println (total/1000000000)*

}OUTPUT:
Merge Sort Test

Enter number of integer elements


20

Enter 20 integer elements


18 14 7 11 9 0 2 6 8 5 4 18 2 12 2 7 19 11 6 18
Elements after sorting
0 2 2 2 4 5 6 6 7 7 8 9 11 11 12 14 18 18 18 19
5.9923E-5

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

a)Dynamic programming method

import java.util.Scanner;

public class knapsack_dynamic {

public static int max(int a,int b)


{
return((a>b)?a:b);
}
public static void main(String[] args)
{
int n,m,i,j,profit=0;
int w[]= new int[10];
int p[]= new int[10];
int v[][] = new int[10][10];
int x[]= new int[10];
Scanner scan = new Scanner( System.in );
/* Accept number of elements */
System.out.println("Enter number of objects");
n = scan.nextInt();
System.out.println("Enter capacity of knapsack");
m = scan.nextInt();

/* Create array of n elements */

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


{ System.out.println("\nEnter the weight and profit
of"+i+"object");
/* knap.w[i]= scan.nextInt();
knap.p[i]= scan.nextInt();*/
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;
else if (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.println("The Resultant profit table:");

for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
System.out.print("\t"+v[i][j]);
}
System.out.println("\n");
}
for(i=0;i<=n;i++)
x[i]=0;
i=n; //Number of Objects
j=m; //Capacity of Knapsack
while(i!=0 && j!=0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1; //objects selected
j=j-w[i]; //Remaining capacity
}
i--;
}
System.out.println("\nThe objects selected are :\n");
for(i=1;i<=n;i++)
{
if(x[i]==1)
System.out.print("\t"+i);
}
System.out.println("\n");
System.out.println("\nOptimal solution is "+profit);

OUTPUT:

Enter number of objects


4
Enter capacity of knapsack
5

Enter the weight and profit of1object


2 12

Enter the weight and profit of2object


1 10

Enter the weight and profit of3object

3 20

Enter the weight and profit of4object

2 15
The Resultant profit table:
0 0 0 0 0 0

0 0 12 12 12 12

0 10 12 22 22 22

0 10 12 22 30 32

0 10 15 25 30 37

The objects selected are :

1 2 4

Optimal solution is 37

(b) Greedy method.

import java.util.Scanner;

public class knapsack_greedy {


public static void main(String[] args)
{
double n,m,rc=0,temp;
double profit=0;
int i,j;
double w[]= new double[10];
double p[]= new double[10];

double pp[]= new double[10];


double x[]= new double[10];
Scanner scan = new Scanner( System.in );
/* Accept number of elements */
System.out.println("Enter number of objects");
n = scan.nextInt();
System.out.println("Enter capacity of knapsack");
m = scan.nextInt();

/* Create array of n elements */


for (i = 0; i<n; i++)
{ System.out.println("\nEnter the weight and profit of"+i+"object");

w[i]= scan.nextInt();
p[i]= scan.nextInt();
pp[i]= p[i]/w[i];
}

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


{
for (j =0; j<n-i-1; j++)
{
if(pp[j]<pp[j+1])
{
temp=pp[j];
pp[j]=pp[j+1];
pp[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("PP ARRAY \n");
for (i =0; i<n; i++)
System.out.println("\t"+pp[i]+"\t"+w[i]+"\t"+p[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[i];
else
x[i]=1;
profit=profit + x[i]*p[i];
System.out.println("\nprofit is "+profit+"\t"+x[i]+"\t"+p[i]);
rc=rc-w[i];
}

System.out.println("\nprofit is "+profit);
}
}

OUTPUT:
Enter number of objects
4
Enter capacity of knapsack
5

Enter the weight and profit of0object


2 12

Enter the weight and profit of1object


1 10

Enter the weight and profit of2object


3 20

Enter the weight and profit of3object


2 15
PP ARRAY

10.0 1.0 10.0


7.5 2.0 15.0
6.666666666666667 3.0 20.0
6.0 2.0 12.0

profit is 10.0 1.0 10.0

profit is 25.0 1.0 15.0

profit is 38.33333333333333 0.6666666666666666 20.0

profit is 38.33333333333333

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;
public class dijkstra
{
public static void dijkstra_soln(int n,int src,int cost[][])
{
int i,j,min;
int dis[]=new int[10];
int vis[]=new int[10];
for(i=1;i<=n;i++)
{
dis[i]=cost[src][i];
}
vis[src]=1; //starting vertex is included in S
for(i=1;i<=n-1;i++)
{
min=999;
int u=0;
for(j=1;j<=n;j++)
{
if(vis[j]==0 && (dis[j]<min))//Find the smallest element in the
Dist(u)
{
min=dis[j];
u=j;
}

vis[u]=1;
for(j=1;j<=n;j++)
{
if(vis[j]==0 &&((dis[u]+cost[u][j])<dis[j]))//Upadate the Dist[]
Matrix
{
dis[j]=(dis[u]+cost[u][j]);

}
}
}
for(i=1;i<=n;i++)
{
System.out.println(src+"-> "+i+"= "+dis[i]);

}
}

public static void main(String[] args)


{
Scanner scan = new Scanner( System.in );
int n,src,i,j;
/* Accept number of elements */
System.out.println("Enter number of vertices");
n = scan.nextInt();
System.out.println("Enter source vertex");
src = scan.nextInt();
System.out.println("Enter cost adjacent matrix");
/* Create array of n elements */
int cost[][] = new int[10][10];
int vis[]=new int[10];
for (i = 1; i <=n; i++)
{ for (j= 1; j<=n; j++)
cost[i][j]= scan.nextInt();
vis[i]=0;

System.out.println("\nSingle source shortest path soln ");


dijkstra_soln(n,src,cost);
}
}

OUTPUT:
Enter number of vertices
5
Enter source vertex

1
Enter cost adjacent matrix
0 3 999 7 999
3 0 4 2 999
999 4 0 5 6
7 2 5 0 4
999 999 6 4 0

Single source shortest path soln


1-> 1= 0
1-> 2= 3
1-> 3= 7
1-> 4= 5
1-> 5= 9

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.utl.**
public class Kruskals
{
public int p[]=new int[10]*
public int cost[][]=new int[10][10]*
public int fni(int v)
{
while(p[v]!=0)
v=p[v]*
return v*
}
public voii union(int i,int j)
{
if(i<j)
p[j]=i*
else
p[i]=j*
}
voii Kruskal_Algo(int n)
{
int i,j,u,v,min,a=0,b=0,ne=1,mincost=0*
while(ne<n)
{
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!=999)
{
u=fni(a)*v=fni(b)*
cost[a][b]=cost[b][a]=999*
if(u!=v)
{
System.out.println(ne++ +"eige("+a+","+b+")-->"+min)*
mincost+=min*
union(u,v)*
}
}

}
System.out.println("Cost of Spanning tree:"+mincost)*
}
public statc voii main(String[] args)
{
Kruskals K=new Kruskals()*
int i,j,n*
int cost[][]=new int[10][10]*
Scanner s=new Scanner(System.in)*
System.out.println("Enter the number of vertces:")*
n=s.nextInt()*
System.out.println("Enter the cost aijacency matrix:")*
for(i=1*i<=n*i++)
{
for(j=1*j<=n*j++)
K.cost[i][j]=s.nextInt()*
if(K.cost[i][j]==0)
K.cost[i][j]=999*
}
System.out.println("Kruskal's Soluton")*
K.Kruskal_Algo(n)*
}
}

OUTPUT:
Enter the number of vertces:
4
Enter the cost aijacency matrix:
0152
1 0 999 999
5 999 0 3
2 999 3 0
Kruskal's Soluton
1eige(1,2)-->1
2eige(1,4)-->2
3eige(3,4)-->3
Cost of Spanning tree:6

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

public class prims


{
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
int n,i,j;
int a=0,b=0,u=0,ne=1,v=0;
int min,mincost=0;

/* Accept number of elements */


System.out.println("Enter number of vertices");
n = scan.nextInt();
System.out.println("Enter cost adjacent matrix");
/* Create array of n elements */
int cost[][] = new int[10][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("\nprims soln ");


for(i=1;i<=n;i++)
visited[i]=0; //Intialize all vertices as unvisited
System.out.println("\n The edges of spanning tree are :\n");
visited[1]=1; // Consider vertex 1 as starting
while(ne<n)
{
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
{
min=cost[i][j]; //assigning the minimum cost
a=u=i;
b=v=j;
}
}
}
}
if(visited[u]==0||visited[v]==0)
{
System.out.println(ne++ +" edge "+"("+ a +","+ b +")"+ min);
//print the Minimum edges
mincost+=min; //Add minimum edge to spanning tree
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
System.out.println("Minimum cost"+ mincost);

OUTPUT:
Enter number of vertices
5
Enter cost adjacent matrix
0 11 9 7 8
11 0 15 14 13
9 15 0 12 14
7 14 12 0 6
8 13 14 6 0

prims soln

The edges of spanning tree are :

1 edge (1,4)7
2 edge (4,5)6
3 edge (1,3)9
4 edge (1,2)11
Minimum cost33

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.
Implement All-Pairs Shortest Paths problem using Floyd's algorithm
import java.util.Scanner;

public class floyds


{
public static int min(int a,int b)
{
return((a<b)?a:b);
}
public static void floyds_soln(int a[][],int n)
{
int i,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]);
}

public static void main(String[] args)


{ int n,i,j;
Scanner scan = new Scanner( System.in );
/* Accept number of elements */
System.out.println("Enter number of vertices");
n = scan.nextInt();
System.out.println("Enter distance matrix");
/* Create array of n elements */
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("\nFloyds soln ");
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]+" ");
System.out.println("\n");

}
}

OUTPUT:

Enter number of vertices


4
Enter distance matrix
0 999 3 999
2 0 999 999
999 7 0 1
6 999 999 0

Floyds soln
Shortest path length matrix
0 10 3 4

2 0 5 6

7 7 0 1

6 16 9 0

10 Write Java programs to


b)Implement Travelling Sales Person problem using Dynamic programming.

import java.utl.Scanner*

public class Lab9B

public statc voii main(String[] args)

int c[][]=new int[10][10], tour[]=new int[10]*

scanner in = new Scanner(System.in)*

int i, j,cost*

System.out.println("**** TSP DYNAMIC PROGRAMMING *******")*

System.out.println("Enter the number of cites: ")*

int n = in.nextInt()*

if(n==1)

System.out.println("Path is not possible")*

System.exit(0)*

System.out.println("Enter the cost matrix")*

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

for(j=1*j<=n*j++)

c[i][j] = in.nextInt()*

System.out.println("The enterei cost matrix is")*

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

for(j=1*j<=n*j++)

System.out.print(c[i][j]+"\t")*

System.out.println()*
}

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

tour[i]=i*

cost = tspip(c, tour, 1, n)*

System.out.println("The accurate path is")*

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

System.out.print(tour[i]+"->")*

System.out.println("1")*

System.out.println("The accurate mincost is "+cost)*

System.out.println("******* ************* ***************")*

statc int tspip(int c[][], int tour[], int start, int n)

int mintour[]=new int[10], temp[]=new int[10], mincost=999, ccost, i, j, k*

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[start]][tour[i]]+(ccost=tspip(c,temp,start+1,n)))<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]*

return mincost*

OUTPUT:
**** TSP DYNAMIC PROGRAMMING *******
Enter the number of cities:
4
Enter the cost matrix
0 10 15 20
5 0 9 10
6 13 0 12
8 8 9 0
The entered cost matrix is
0 10 15 20
5 0 9 10
6 13 0 12
8 8 9 0
The accurate path is
1->2->4->3->1
The accurate mincost is 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 sum_of_subsets {


public int d ,n, count=0,i;
public int w[]=new int[10];
public int x[]=new int[10];

public void sumofsubsets(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.println(" " + w[i]);
System.out.println("\n");
}

else if ( s + w[k] + w[k+1] <= d)


sumofsubsets(s+w[k], k+1, r-w[k]);

if( ( s + r - w[k] >= d) && ( s + w[k+1]) <= d)


{
x[k] = 0;
sumofsubsets(s,k+1,r-w[k]);
}
}

public static void main(String[] args)


{ sum_of_subsets ss=new sum_of_subsets();
int i,n,sum=0;
Scanner scan = new Scanner( System.in );
System.out.println("Enter number of elements");
n = scan.nextInt();
System.out.println("Enter the elements");
for(i=1;i<=n;i++)
ss.w[i] = scan.nextInt();
System.out.println("Enter the sum");
ss.d = scan.nextInt();
for( i = 1; i <= n; i++)
{
ss.x[i] = 0;
sum = sum + ss.w[i];
}
if ( ( sum < ss.d ) || ( ss.w[1] > ss.d ) )

System.out.println("\n\n No subset possible\n");


else
ss.sumofsubsets(0,1,sum);

}
}

OUTPUT 1:

Enter number of elements


5
Enter the elements

1 2 5 6 8
Enter the sum
9
subset = 1
1
2
6

subset = 2
1
8

OUTPUT 2:
Enter number of elements
4
Enter the elements
2 4 6 8
Enter the sum
10
subset = 1
2
8

subset = 2
4
6
OUTPUT 3:
Enter number of elements
4
Enter the elements

1
2
3
3
Enter the sum
12

No subset possible

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.Scanner;

public class hamiltonian {

public int x[]=new int[25];


public void Next_Vertex(int G[][],int n,int k)
{
int j;
boolean flag=true;
while(flag)
{
//obtain next vertex
x[k]=(x[k]+1)%(n+1);
if(x[k]==0)
return;
if(G[x[k-1]][x[k]]!=0)
{ //if edge between k and k-1 is present
for(j=1;j<=k-1;j++)//every adjacent vertex
{
if(x[j]==x[k])//not a distinct vertex
break;
}
if(j==k) //obtain a distinct vertex
{
if((k<n)||((k==n)&&(G[x[n]][x[1]]!=0)))
return;//return a distinct vertex
}
}
}
}
public void H_Cycle(int G[][],int n,int k)
{
int i;
boolean flag=true;
while(flag)
{
Next_Vertex(G,n,k);//generates next legal vertex for determining cycle
if(x[k]==0)
return;

if(k==n)
{
System.out.println("\n");
for(i=1;i<=n;i++)
System.out.print("\t"+x[i]); //printing Hamiltonian cycle
System.out.print("\t"+x[1]);
}
else
H_Cycle(G,n,k+1);
}
}
public static void main(String[] args)
{ hamiltonian ham=new hamiltonian();
int i,j,v1,v2,Edges,n;
int G[][]=new int[20][20];
Scanner scan = new Scanner( System.in );
System.out.println("\n\t Program for Hamiltonian Cycle ");
System.out.println("\n Enter the number of vertices of 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("\n Enter the total number of edges: ");
Edges = scan.nextInt();
for(i=1;i<=Edges;i++)
{
System.out.println("\n Enter the edge: ");
v1 = scan.nextInt();
v2 = scan.nextInt();
G[v1][v2]=1;
G[v2][v1]=1;
}

ham.x[1]=1;
System.out.println("\n Hamiltonian cycle ...\n");
ham.H_Cycle(G,n,2);
}

OUTPUT:

Program for Hamiltonian Cycle

Enter the number of vertices of graph:


6

Enter the total number of edges:


10

Enter the edge:


1
2

Enter the edge:


1
3

Enter the edge:


1
4

Enter the edge:


2
3

Enter the edge:


2
5

Enter the edge:


2
6

Enter the edge:


3
4

Enter the edge:


3
5

Enter the edge:


4
5

Enter the edge:


5
6

Hamiltonian cycle ...


1 2 6 5 3 4 1

1 2 6 5 4 3 1

1 3 2 6 5 4 1

1 3 4 5 6 2 1

1 4 3 5 6 2 1

1 4 5 6 2 3 1

You might also like