DAA Lab Manual - 25042017
DAA Lab Manual - 25042017
DAA Lab Manual - 25042017
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 a) 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.
b) Write a Java program to implement the Stack using arrays. Write Push(),
Pop(), and display() methods to demonstrate its working.
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 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
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.
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.
Programs
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create n Student objects and print the USN,
Name, Branch, and Phone of these objects with suitable headings.
Scanner:
Scanner is a class in java.util package used for obtaining the input of the
primitive types like int, double etc. and strings.
To create an object of Scanner class, we usually pass the predefined
object System.in, which represents the standard input stream. We may pass
an object of class File if we want to read input from a file.
To read numerical values of an integer data type, the function to use is
nextInt ().
For example, to read a value of type long, we can use nextLong()
To read strings, we use nextLine().
Program 1a
package Students;
import java.util.*;
public class Student
{
String usn;
String name;
String branch;
long phone;
void getDetails()
{
Scanner in=new Scanner(System.in);
}
for(i=0;i<n;i++)
{
System.out.println("\nThe details of Student" +(i+1));
a[i].putDetails();
}
}
}
Output:
Enter the number of students
2
Enter details of Student1
Enter the Student USN
1MV15CS001
Enter the Student Name
Anil
Enter the Student Branch
CSE
Enter the Student phone
1234532728
Enter details of Student2
Enter the Student USN
1MV15IS005
Enter the Student Name
Basawaraj
Enter the Student Branch
ISE
Enter the Student phone
1237464725
The details of Student1
USN:1MV15CS001
Name:Anil
Branch:CSE
Phone:1234532728
Arrays: Java array is an object that contains elements of similar data type.
Syntax to Declare an Array in java
dataType[] arr; OR dataType arr[];
Program 1b
package Students;
import java.util.*;
class StackMethods
{
int top;
int size;
int[] stack ;
public StackMethods(int arraySize)
{
size=arraySize;
stack= new int[size];
top=-1;
}
public void push(int value)
{
if(top==size-1)
{
System.out.println("Stack is full, can't push a value");
}
else
{
top=top+1;
stack[top]=value;
}
}
public int pop()
{
int t=0;
if(top==-1)
{
System.out.println("Can't pop...stack is empty");
return -1;
}
else
{
t=top--;
return stack[t];
}
}
public void display()
{
for(int i=top;i>=0;i--)
{
System.out.print(stack[i]+" ");
}
System.out.println("\n");
}
}
public class Stack1
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Stack operations\n");
System.out.println("Enter Size of Stack ");
int n = in.nextInt();
int choice ;
/* Creating object of class arrayStack */
StackMethods stk = new StackMethods(n);
/* Perform Stack Operations */
do{
System.out.println("\nStack Operations");
System.out.println("1. push");
System.out.println("2. pop");
System.out.println("3. display");
System.out.println("Enter the choice");
int ch = in.nextInt();
switch (ch)
{
case 1 : System.out.println("Enter element to push");
stk.push( in.nextInt() );
break;
case 2 :int s=stk.pop();
if (s!=-1)
System.out.println("Popped Element = " + s);
break;
case 3 :stk.display();
break;
}
System.out.println("Do you want to continue press 0/1");
choice=in.nextInt();
}
while(choice==1);
}
}
Output:
Stack operations
Stack Operations
1. push
2. pop
3. display
Enter the choice
3
30 20 10
Do you want to continue press y/n
y
Stack Operations
1. push
2. pop
3. display
Enter the choice
2
Popped Element = 30
Do you want to continue press y/n
y
Stack Operations
1. push
2. pop
3. display
Enter the choice
3
20 10
Do you want to continue press y/n
n
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives
from an existing class. The meaning of "extends" is to increase the
functionality.
Program 2a
package Students;
import java.util.Scanner;
class Staff
{
int staffID;
String sname;
long phone;
float salary;
void getSdetails()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the Staff ID");
staffID=in.nextInt();
System.out.println("Enter the Staff Name");
sname=in.next();
System.out.println("Enter the Staff Phone no");
phone=in.nextLong();
System.out.println("Enter the Staff Salary");
salary=in.nextFloat();
}
void putSdetails()
{
System.out.println("staff ID=" +staffID);
System.out.println("staff Name=" +sname);
System.out.println("staff phone no=" +phone);
System.out.println("staff Salary=" +salary);
System.out.println("\n");
}
}
class Teaching extends Staff
{
String domain;
String publication;
void getTdetails()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the Domain");
domain=in.nextLine();
System.out.println("Enter the Publication");
publication=in.nextLine();
}
void putTdetails()
{
System.out.println("Domain ="+domain);
System.out.println("Publication ="+publication);
System.out.println("\n");
}
}
class Technical extends Staff
{
String skills;
void getT1details()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the Skills");
skills=in.nextLine();
}
void putT1details()
{
System.out.println("Skills ="+skills);
System.out.println("\n");
}
}
class Contract extends Staff
{
String period;
void getCdetails()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the Period");
period=in.nextLine();
}
void putCdetails()
{
System.out.println("period ="+period);
System.out.println("\n");
}
}
class Inheritance
{
public static void main(String args[])
{
int i,n;
System.out.println("Enter the number of staff");
Scanner in=new Scanner(System.in);
n=in.nextInt();
Staff sf[]=new Staff[n];
System.out.println("...............");
}
}
}
Output:
Enter the number of staff
2
Enter the details of staff1
Enter the Staff ID
1111
Enter the Staff Name
manjunath
Enter the Staff Phone no
1223424125
Enter the Staff Salary
30000
Enter the Domain
java
Enter the Publication
sun microsystem
Enter the Skills
core java
Enter the Period
6 months
...............
Enter the details of staff2
Enter the Staff ID
2222
Enter the Staff Name
ramesh
Enter the Staff Phone no
1325378332
Enter the Staff Salary
40000
Enter the Domain
networking
Enter the Publication
pearson
Enter the Skills
protocols
Enter the Period
2 months
...............
The Details of staff1
staff ID=1111
staff Name=manjunath
staff phone no=1223424125
staff Salary=30000.0
Domain =java
Publication =sun microsystem
Domain =networking
Publication =pearson
Skills =protocols
period =2 months
StringTokenizer:
The java.util.StringTokenizer class allows you to break a string into tokens. It
is simple way to break string.
Constructors of StringTokenizer class
There are 3 constructors defined in the StringTokenizer class.
Constructor Description
Program 2b
package staff;
import java.util.Scanner;
import java.util.StringTokenizer;
{
System.out.println("Please enter it in proper format");
System.exit(0);
}
return str;
}
public void displayCustomer(String data)
{
String st = data.substring(0, data.length());
StringTokenizer token = new StringTokenizer(st, "<,/>");
String finalString =null;
while(token.hasMoreTokens())
{
if(finalString == null)
{
finalString = token.nextToken();
}
else
{
finalString =finalString+","+token.nextToken();
}
}
System.out.println("The Resultant String is:" +"<"
+finalString+">");
}
public static void main(String args[])
{
Customerc = new Customer();
String data=c.readCustomer();
c.displayCustomer(data);
}
}
Output:
Q3a) Write a Java program to read two integers a and b. Compute a/b and
print, when b is not zero. Raise an exception when b is equal to zero.
Exception Handling:
The exception handling in java is one of the powerful mechanism to handle
the runtime errors so that normal flow of the application can be maintained.
1. try
2. catch
3. finally
4. throw
5. throws
try block
Java try block is used to enclose the code that might throw an exception. It must
be used within the method. try block must be followed by either catch or finally
block.
try{
//code that may throw exception
}catch(Exception_class_Name ref){ }
Program 3a
package Exception;
import java.util.Random;
import java.util.Scanner;
a=in.nextInt();
System.out.println("Enter the value of b");
b=in.nextInt();
try
{
d=a/b;
System.out.println("\nThe Result of "+a+"/"+b+ " is:"+d);
}
catch(ArithmeticException ae)
{
System.out.println("division by zero");
}
}
}
Output:
Enter the value of a
10
Enter the value of b
2
The Result of 10/2 is:5
Do you want to continue press y/n
y
Enter the value of a
5
Enter the value of b
0
division by zero
Do you want to continue press y/n
Multithreading:
Multithreading in java is a process of executing multiple threads
simultaneously.
Thread class:
Thread class provide constructors and methods to create and perform operations
on a thread.Thread class extends Object class and implements Runnable
interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
Runnable interface:
The Runnable interface should be implemented by any class whose instances
are intended to be executed by a thread. Runnable interface have only one
method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It
performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will
run.
class Multi3 implements Runnable{
1. public void run(){
2. System.out.println("thread is running...");
3. }
4. public static void main(String args[]){
5. Multi3 m1=new Multi3();
6. Thread t1 =new Thread(m1);
7. t1.start();
8. }
9. }
10.
Program 3b
package Exception;
import java.util.Random;
import java.util.Scanner;
int n,i;
public void run()
{
Scanner in=new Scanner(System.in);
Random rand=new Random();
n=rand.nextInt(50);
System.out.println("\nEnter the number of elements");
n=in.nextInt();
int arr[]=new int[n];
for(i=0;i<n;i++)
arr[i]=rand.nextInt(50);
System.out.println("\nthe random elements are ");
for(i=0;i<n;i++)
System.out.println(arr[i]+" ");
}
}
Output:
Enter number to find square
4
The square of number is:16
Enter number to find cube
5
The cube of number is: 125
Enter the number of elements
3
the random elements are
48
2
12
Q4. 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.
Quick Sort divides the array according to the value of elements. It rearranges
elements of a given array A[0..n-1] to achieve its partition, where the elements
before position s are smaller than or equal to A[s] and all the elements after
position s are greater than or equal to A[s].
Pseudocode : QUICKSORT(a[l..r])
//Sorts a subarray by quicksort
//Input: A subarray A[l..r] of A[0..n-1],defined by its left and right indices l and
r
//Output: Subarray A[l..r] sorted in nondecreasing order
{
if l<r
{
s← Partition(A[l..r]) //s is a split position
QUICKSORT(A[l..s-1])
QUICKSORT(A[s+1..r])
}
}
Pseudocode : Partition(A[l..r])
//Partition a subarray by using its first element as its pivot
//Input:A subarray A[l..r] of A[0..n-1],defined by its left and right indices l and r
(l<r)
//Output:A partition of A[l..r], with the split position returned as this function’s
value
{
p ← A[l]
i ← l; j ← r+1
repeat
{
repeat i ← i+1 until A[i] >=p
repeat j ← j-1 until A[j] <=p
swap(A[i],A[j])
} until i>=j
swap(A[i],A[j]) // undo last swap when i>=j
swap(A[l],A[j])
return j
}
Program 4
package sort;
import java.util.Random;
import java.util.Scanner;
a[i]=a[j];
a[j]=temp;
}
}
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;
}
public static void qs (int a[],int low, int high)
{
int mid;
if(low<high)
{
mid=partition(a,low,high);
qs(a,low,mid-1);
qs(a,mid+1,high);
}
}
public static void main(String args[])
{
int n,i;
Scanner in=new Scanner(System.in);
Random rand=new Random();
System.out.println("Quicksort Test");
/* Accept no.of Elements */
System.out.println("\nEnter the number of elements");
n=in.nextInt();
Output:
Quicksort Test
Note: For n=5000 to 50000 in step of 5000 note down the time in nanoseconds.
Convert time in seconds and plot the graph with n as x axis and time as y axis.
Q5.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.
Merge sort is a perfect example of a successful application of the divide and conquer
technique. It sorts a given array a[0…n-1] by dividing it into two halves a[0….mid-1]
and a[mid+1….high],sorting each of them recursively, and then merging the two
smaller sorted arrays into a single sorted one.
if a[h]<=a[j] then
{
b[i] <- a[h]
h++
}
else
{
b[i] <- a[j]
j++
}
i++
}
if h>mid then
for k=j to high do
{
b[i] <- a[k]
i++
}
else
for k=h to mid do
{
b[i] <- a[k]
i++
}
for k=low to high do
a[k] <- b[k]
}
Program 5
package sort1;
import java.util.Random;
import java.util.Scanner;
{
c[k]=a[i];
i=i+1;
}
else
{
c[k]=a[j];
j=j+1;
}
k=k+1;
}
while(i<=mid)
{
c[k]=a[i];
k=k+1;
i=i+1;
}
while(j<=high)
{
c[k]=a[j];
k=k+1;
j=j+1;
}
for(i=low;i<=high;i++)
a[i]=c[i];
}
public static void main(String args[] )
{
int n,i;
Scanner in=new Scanner(System.in);
Random rand=new Random();
System.out.println("MergeSort Test");
/* Accept no.of Elements */
System.out.println("\nEnter the number of elements");
n=in.nextInt();
/* create array of n elements */
int arr[]=new int[max];
try{
/* Generate Random Numbers */
for(i=0;i<n;i++)
arr[i]=rand.nextInt(100);
/* Print random numbers */
System.out.println("\nthe random elements are ");
for(i=0;i<n;i++)
System.out.println(arr[i]+" ");
long start_time=System.nanoTime();
/*call method merge Sort*/
mergesort(arr,0,n-1);
long end_time=System.nanoTime();
/* Print Sorted Array */
System.out.println("\nThe Elements After sorting");
for(i=0;i<n;i++)
System.out.println(arr[i]+" ");
long t=end_time - start_time;
System.out.println(“Time taken for execution is:”+t+” nanoseconds);
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("Array Index reached maximum ");
}
}
}
Output:
MergeSort Test
48
52
53
54
59
66
71
84
97
Time taken for execution is:21316 nanoseconds
Note: For n=5000 to 50000 in step of 5000 note down the time in nanoseconds.
Convert time in seconds and plot the graph with n as x axis and time as y axis.
Given weights and values of n items, put these items in a knapsack of capacity
W to get the maximum total value in the knapsack. In other words, given two
integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights
associated with n items respectively. Also given an integer W which represents
knapsack capacity, find out the maximum value subset of val[] such that sum of
the weights of this subset is smaller than or equal to W. You cannot break an
item, either pick the complete item, or don’t pick it (0-1 property).
A simple solution is to consider all subsets of items and calculate the total
weight and value of all subsets. Consider the only subsets whose total weight is
smaller than W. From all such subsets, pick the maximum value subset.
Optimal Substructure:
To consider all subsets of items, there can be two cases for every item:
(1) the item is included in the optimal subset, (2) not included in the optimal set.
Therefore, the maximum value that can be obtained from n items is max of
following two values.
1) Maximum value obtained by n-1 items and W weight (excluding nth item).
2) Value of nth item plus maximum value obtained by n-1 items and W minus
weight of the nth item (including nth item).
If weight of nth item is greater than W, then the nth item cannot be included and
case 1 is the only possibility.
max(a,b)
{
return(a>b)?a:b;
}
knap(i, j)
{
if(i=0 or j=0) then
v[i][j]=0
elseif(j<w[i]) then
v[i][j]=knap(i-1,j)
else
v[i][j]=max(knap(i-1,j), value[i]+knap(i-1,j-w[i]))
returnv[i][j]
}
optimal( i,j)
{
if(i>=1 or j>=1) then
if(v[i][j]!=v[i-1][j]) then
{
Print Item i
b[i]=1
j=j-w[i]
optimal(i-1,j)
}
else
optimal(i-1,j);
}
Program 6a
package knapsack;
import java.util.Scanner;
public class Knapsack1
{
private static int w[]=new int[10];
private static int b[]=new int[10];
private static int v[][]=new int[10][10];
private static int value[]=new int[10];
static int max(int a,int b)
{
return(a>b)?a:b;
}
static int knap(int i,int j)
{
if(i==0 || j==0)
v[i][j]=0;
elseif(j<w[i])
v[i][j]=knap(i-1,j);
else
v[i][j]=max(knap(i-1,j), value[i]+knap(i-1,j-w[i]));
returnv[i][j];
}
static void optimal(int i,int j)
{
if(i>=1 || j>=1)
if(v[i][j]!=v[i-1][j])
{
System.out.println("Item:"+i);
b[i]=1;
j=j-w[i];
optimal(i-1,j);
}
else
optimal(i-1,j);
}
public static void main(String[] args)
{
int profit, w1,n,i,j;
Scanner sc=new Scanner(System.in);
System.out.println("enter the number of items:");
n=sc.nextInt();
System.out.println("enter the capacity of the knapsack:");
w1=sc.nextInt();
System.out.println("enter the values:");
for(i=1;i<=n;i++)
value[i]=sc.nextInt();
System.out.println("enter the weights:");
for(i=1;i<=n;i++)
w[i]=sc.nextInt();
profit=knap(n,w1);
System.out.println("profit: "+profit);
System.out.println("\noptimal subset is:\n");
optimal(n,w1);
System.out.println("the solution vector is:");
for(i=1;i<=n;i++)
System.out.println(b[i]);
}
}
Output:
enter the number of items:
4
enter the capacity of the knapsack:
2
enter the values:
3
45
4
3
enter the weights:
1
1
1
1
profit: 49
Item:3
Item:2
the solution vector is:
0
1
1
0
Pseudocode: GreedyKnapsack(m,n)
//p[1:n] and w[1:n] – contains the profits and weights of n objects ordered such
that
//p[i]/w[i] >= p[I+1]/w[i+1]
//m is size of knapsack and x[1:n] is the solution vector
{
for i<- 1 to n do
x[i]=0.0
u <- m
for i <- 1 to n do
{
if (w[i] > u) then break
x[i] <- 1.0
u <- u-w[i]
}
if (i<=n) then
x[i]=u / w[i]
}
Program 6b
package knapsack;
import java.util.Scanner;
public class Knapsack2
{
public static void knapsack(int n, int item[],float weight[], float profit[], float
capacity)
{
float tp = 0,u;
int i;
u = capacity;
float x[]=new float[20];
for (i = 0; i < n; i++)
x[i] = (float) 0.0;
for (i = 0; i < n; i++)
{
if (weight[i] > u)
break;
else {
x[i] = (float) 1.0;
tp = tp + profit[i];
u = (int) (u - weight[i]);
}
}
if (i < n)
x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]);
System.out.println("\nThe result vector is:- ");
for (i = 0; i < n; i++)
System.out.println("\tItem "+item[i]+":" +x[i]);
System.out.println("\nMaximum profit is:- " +tp);
}
public static void main(String[] args)
{
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
temp=item[j];
item[j]=item[i];
item[i]=(int)temp;
}
}
}
knapsack(num, item,weight, profit, capacity);
}
}
Output:
Enter the no. of objects:-
3
3 10 15
1 18 25
For a given vertex called the source in a weighted connected graph, find the
shortest paths to all its other vertices. Dijkstra’s algorithm is the best known
algorithm for the single source shortest paths problem. This algorithm is
applicable to graphs with nonnegative weights only and finds the shortest paths
to a graph’s vertices in order of their distance from a given source. It finds the
shortest path from the source to a vertex nearest to it, then to a second nearest,
and so on. It is applicable to both undirected and directed graphs
Example:
2
1
2
3
4
3
Pseudocode:
findmin( )
{
for i ← to n do
if (s[i] = 0) do
{
min ← i
break
}
for i ← 1 to n do
{
if (d[i]<d[min] & s[i]=0)
min ← i
}
return min
}
dijkstra( )
{
for i ← to n do
{
s[i] ← 0
d[i] ← 999
p[i] ← 0
}
d[v] ← 0
for k ← 1 to n do
{
u ← findmin( )
s[u] ← 1
for w1 ←1 to n do
{
if (w[u][w1]!=999 & s[w1] = 0)
{
if (d[w1]>d[u]+w[u][w1] )
{
d[w1] ← d[u]+w[u][w1]
p[w1] ←u
}
}
}
}
display "shortest path costs"
for i ←1 to n do
{
if (d[i]=999)
display "sorry! no path for source v to vertex i"
else
display “path cost from v to i is d[i]”
}
display "shortest group of paths are"
for i ←1 to n do
{
if i!=v & d[i]!=999
{
display i
j ←p[i]
while p[j]!=0 do
{
print "" j
j ← p[j];
}
print ""v
}
}
}
main( )
{
accept number of vertices n
accept weight matrix 999 for ∞
accept source vertex
call dijkstra( )
}
Program 7
package shortestpath;
import java.util.Scanner;
public class Dijkstra
{
public static int findmin()
{
int i,n,min=0;
int d[]=new int[20];
int s[]=new int[20];
d[v]=0;
for(k=1;k<=n;k++)
{
u=findmin();
s[u]=1;
for(w1=1;w1<=n;w1++)
{
if(w[u][w1]!=999 && s[w1]==0)
{
if(d[w1]>d[u]+w[u][w1])
{
d[w1]=d[u]+w[u][w1];
p[w1]=u;
}
}
}
}
System.out.println("shortest path costs\n");
for(i=1;i<=n;i++)
{
if(d[i]==999)
System.out.println("sorry! no path for source" + v + "to" + i +
"vertex");
else
System.out.println("path cost from" +v+ "to" +i+ "is:" +d[i]+"\n");
}
System.out.println("shortest group of paths are\n");
for(i=1;i<=n;i++)
{
if(i!=v && d[i]!=999)
{
System.out.print(i);
j=p[i];
while(p[j]!=0)
{
System.out.println("<----"+ j +" ");
j=p[j];
}
System.out.println("<----"+ v +"\n");
}
}
}
public static void main(String args[])
{
int i,j,n,v;
int d[]=new int[20];
int s[]=new int[20];
int w[][]=new int[50][50];
Dijikstra d1 = new Dijikstra();
Scanner in=new Scanner(System.in);
System.out.println("enter the number of vertices\n");
n=in.nextInt();
System.out.println("enter the cost of vertices\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
w[i][j]=in.nextInt();
}
System.out.println("enter the source vertex\n");
v=in.nextInt();
/* call Dijkstra method */
d1.dijkstra(v,w,s,d,n);
}
}
Output:
enter the number of vertices
3
enter the cost of vertices
999 2 3
2 999 4
3 4 999
enter the source vertex
1
shortest path costs
path cost from1to1is:0
path cost from1to2is:2
path cost from1to3is:3
shortest group of paths are
2<----1
3<----1
2. Pick the smallest edge. Check if it forms a cycle with the spanning tree
formed so far. If cycle is not formed, include this edge. Else, discard it.
3. Repeat step2 until there are (V-1) edges in the spanning tree.
The step2 uses Union-Find algorithm to detect cycle.
In this post, we will discuss an application of Disjoint Set Data Structure. The
application is to check whether a given graph contains a cycle or not.
Pseudocode: Kruskal(G)
//Kruskal’s algorithm for constructing a minimum spanning tree
// Input: A weighted connected graph G=V, E
// Output: E T , the set of edges composing a minimum spanning tree
of G
Sort E in non-decreasing order of the edge weights w(ei1)<=…
<=w(ei|E|)
ET ; ecounter 0 //initialise the set of tree edges and its size
k0 //initialise the number of processed edges
while ecounter < |V| - 1
kk+1
if ET {eik}is acyclic
ETET {eik}; ecounter ecounter+1
return ET
Program 8
package shortest;
import java.util.Scanner;
public class Kruskal
{
for(j=0;j<n;j++)
{
if(c[i][j]!=0 && c[i][j]<min)
{
min=c[i][j];
u=i;
v=j;
}
}
}
if(min==999) break;
i=find(u,s);
j=find(v,s);
if(i!=j)
{
t[k][0]=u;
t[k][1]=v;
k++;
count++;
sum+=min;
union1(i,j,s);
}
c[u][v]=c[v][u]=999;
}
if(count==n-1)
{
System.out.println("cost of spanning tree=" +sum+ "\n");
System.out.println("spanning tree is\n");
for(k=0;k<n-1;k++)
{
System.out.println("\n"+t[k][0]+","+t[k][1]);
}
}
System.out.println("spanning treee doesn't exist");
}
public static void main(String args[])
{
int n,i,j;
int c[][]=new int[10][10];
Scanner in=new Scanner(System.in);
System.out.println("Enter no of nodes\n");
n=in.nextInt();
System.out.println("Enter the cost adjacency matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=in.nextInt();
}
}
kruskal(n,c);
}
}
Output:
Enter no of nodes
6
Enter the cost adjacency matrix
999 3 999 999 6 5
3 999 1 999 999 4
999 1 999 6 999 4
999 999 6 999 8 5
6 999 999 8 999 2
5 4 4 5 2 999
cost of spanning tree=15
spanning tree is
1,2
4,5
0,1
1,5
3,5
Pseudocode:Prim(G)
//Prim’s algorithm for constructing a minimum spanning tree
//Input: A weighted connected graph G = {V, E}
//Output: Et, the set of edges composing a minimum spanning tree of G
Vt←{v0} //the set of tree vertices can be initialized with any vertex
Et←∅
for i ←1 to |V| − 1 do
find a minimum-weight edge e∗ = (v∗, u∗) among all the edges (v, u)
such that v is in Vtand u is in V − Vt
Vt←Vt ∪ {u∗}
Et←Et∪ {e∗}
return Et
Program 9
package mincost;
import java.util.Scanner;
public class prims
{
public static void main(String args[])
{
int n,i,j,min=0,a=0,u = 0,b=0,v = 0,source;
int ne=1;
int min_cost=0;
int cost[][]=new int[20][20];
int visited[]=new int[20];
Scanner in=new Scanner(System.in);
System.out.println("Enter the no. of nodes:");
n=in.nextInt();
System.out.println("Enter the cost matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cost[i][j]=in.nextInt();
}
}
for(i=1;i<=n;i++)
visited[i]=0;
System.out.println("Enter the root node:");
source=in.nextInt();
visited[source]=1;
System.out.println("\nMinimum cost spanning tree is\n");
while(ne<n)
{
min=999; for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min) if(visited[i]==0)
continue;
else
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
if(visited[u]==0||visited[v]==0)
{
ne++;
System.out.println("\nEdge" + ne + "\t" +a+ "->" +b+ "=" +min+"\n");
min_cost=min_cost+min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
System.out.println("\nMinimum cost="+min_cost+"\n");
}
}
Output:
Enter the no. of nodes:
4
Enter the cost matrix:
999 1 5 2
1 999 999 999
5 999 999 3
2 999 3 999
Enter the root node:
1
Minimum cost spanning tree is
Edge21->2=1
Edge31->4=2
Edge44->3=3
Minimum cost=6
this matrix indicates the length of the shortest path from the ith vertex to the jth
vertex. We can generate the distance matrix with an algorithm that is very
similar to Warshall’s algorithm. It is called Floyd’s algorithm after its co-
inventor Robert W.Floyd. It is applicable to both undirected and directed
weighted graphs provided that they do not contain a cycle of a negative length.
(The distance between any two vertices in such a cycle can be made arbitrarily
small by repeating the cycle enough times.) The algorithm can be enhanced to
find not only the lengths of the shortest paths for all vertex pairs but also the
shortest paths themselves
Floyd’s algorithm computes the distance matrix of a weighted graph with n
vertices through a series of n × n matrices:
D(0), . . . , D(k−1), D(k), . . . , D(n).
Program 10
package floyd;
import java.util.Scanner;
public class Floyds {
public static void floyd(int a[][],int n)
{
int i,j,k;
int d[][]=new int[10][10];
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
d[i][j]=a[i][j];
}
}
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
}
}
System.out.println("\nThe distance matrix is\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(+d[i][j]+"\t");
}
System.out.println("\n");
}
}
public static int min (int a,int b)
{
if(a<b)
return a;
else
return b;
}
public static void main(String args[])
{
int n,i,j;
int a[][]=new int[10][10];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no.of nodes : ");
n=sc.nextInt();
System.out.println("\nEnter the cost adjacency matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]= sc.nextInt();
floyd(a,n);
}
}
Output:
Enter the no.of nodes :
4
Enter the cost adjacency matrix
0 999 3 999
2 0 999 999
999 7 0 1
6 999 999 0
The distance matrix is
0 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0
Given a set of cities and distance between every pair of cities, the problem is to
find the shortest possible route that visits every city exactly once and returns to
the starting point.
Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian
cycle problem is to find if there exist a tour that visits every city exactly once.
Here we know that Hamiltonian Tour exists (because the graph is complete) and
in fact many such tours exist, the problem is to find a minimum weight
Hamiltonian Cycle.
For example, consider the graph shown in figure on right side. A TSP tour in
the graph is 1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80.The
problem is a famous NP hard problem. There is no polynomial time know
solution for this problem.
Naive Solution:
1) Consider city 1 as the starting and ending point.
2) Generate all (n-1)! Permutations of cities.
3) Calculate cost of every permutation and keep track of minimum cost
permutation.
4) Return the permutation with minimum cost.
Dynamic Programming:
Denote the cities by 1,...,n, the starting city being 1, and let D = (dij) be the
matrix of intercity distances. The goal is to design a tour that starts and ends at
1, includes all other cities exactly once, and has minimum total length. Figure
shows an example involving five cities.
Let's dive right into the DP. So what is the appropriate sub-problem for the
TSP? In this case the most obvious partial solution is the initial portion of a
tour. Suppose we have started at city 1 as required, have visited a few cities, and
are now in city j. What information do we need in order to extend this partial
tour? We certainly need to know j, since this will determine which cities are
most convenient to visit next. And we also need to know all the cities visited so
far, so that we don’t repeat any of them. Here, then, is an appropriate sub-
problem.
For a subset of cities S ⊆ {1,2,...,n} that includes 1, and j ∈ S, let C(S,j) be the
length of the shortest path visiting each node in S exactly once, starting at 1 and
ending at j.
When |S| > 1, we define C(S, 1) = ∞ since the path cannot both start and end at
1.
Now, let’s express C(S,j) in terms of smaller sub-problems. We need to start at
1 and end at j; what should we pick as the second-to-last city? It has to be some
i ∈ S, so the overall path length is the distance from 1 to i, namely, C(S − {j},
i), plus the length of the final edge,dij.
We must pick the best such i:
C(S,j)=mini∈S:i≠jC(S−{j},i)+dij
The sub-problems are ordered by |S|. Here’s the code.
C({1},1) = 0
for s = 2 to n:
for all subsets S ⊆ {1,2,...,n} of size s and containing 1:
C(S,1) = ∞
return minjC({1,...,n},j)+dj1
There are at most 2n.n sub-problems, and each one takes linear time to solve.
Program 10b
package mincost;
import java.util.Scanner;
public class Tsp
{
final static int MAX=100;
final static int INFINITY=999;
static int tsp_dp(int c[][],int tour[],int start,int n)
{
int i,j,k;
int temp[]=new int[MAX];
int mintour[]=new int[MAX];
int mincost,ccost;
if(start==n-2)
return(c[tour[n-2]][tour[n-1]]+c[tour[n-1]][0]);
mincost=INFINITY;
for(i=start+1;i<n;i++)
{
for(j=0;j<n;j++)
temp[j]=tour[j];
temp[start+1]=tour[i];
temp[i]=tour[start+1];
if(c[tour[start]][tour[i]]+
(ccost=tsp_dp(c,temp,start+1,n))<mincost)
{
mincost=ccost+c[tour[start]][tour[i]];
for(k=0;k<n;k++)
mintour[k]=temp[k];
}
}
for(i=0;i<n;i++)
tour[i]=mintour[i];
tour[i]=start;
return mincost;
}
public static void main(String[] args)
{
int n,i,j,cost;
int c[][]=new int[MAX][MAX];
int tour[]=new int[MAX];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of cities:");
n=sc.nextInt();
System.out.println("Enter the cost matrix\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
c[i][j]=sc.nextInt();
for(i=0;i<n;i++)
tour[i]=i;
cost=tsp_dp(c,tour,0,n);
System.out.println("\nmincost by dp:"+cost);
System.out.println("\ntour: ");
for(i=0;i<n;i++)
System.out.print(tour[i]+1 +"\t");
}
}
Output:
Enter the number of cities:
5
Enter the cost matrix
03158
30679
16042
57403
89230
mincost by dp:16
tour:
1 2 4 5 3
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.
Algorithm for Subset
Algorithm for main:
Step 1: accept number of elements
Step 2: accept set of elements
Step 3: accept maximum subset value
Step 4: print the subset cell sum of sub(0,1,sum)
Step 5: stop
Pseudocode: sumofsub(0,1,sum)
{
x[k]=1
if(s +w[k] <- u)
{
print solution v++
for i<- 1 to n do
if x[i]=1
print w[i]
}
else if (s+ w[k] +w[k+] < = m) do
Program 11
package subset;
import java.util.Scanner;
public class Subset
{
private static int d;
private static int count=0;
private static int x[]=new int[20];
private static int w[]=new int[20];
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int i,n,sum=0;
System.out.println("Enter the no. of elements: ");
n=sc.nextInt();
System.out.println("\nEnter the elements in ascending order:\n");
for(i=0;i<n;i++)
w[i]=sc.nextInt();
System.out.println("\nEnter the sum: ");
d=sc.nextInt();
for(i=0;i<n;i++)
sum=sum+w[i];
if(sum<d)
{
System.out.println("No solution\n");
return;
}
subset(0,0,sum);
if(count==0)
{
System.out.println("No solution\n");
return;
}
}
static void subset(int cs,int k,int r)
{
int i;
x[k]=1;
if(cs+w[k]==d)
{
System.out.println("\n\nSubset" +(++count));
for(i=0;i<=k;i++)
if(x[i]==1)
System.out.println(w[i]+" ");
}
else if(cs+w[k]+w[k+1]<=d)
{
subset((cs+w[k]),k+1,r-w[k]);
}
if(cs+r-w[k]>=d && cs+w[k]<=d)
{
x[k]=0;
subset(cs,k+1,r-w[k]);
}
}
}
Output:
Enter the no. of elements:
5
Enter the elements in ascending order:
12568
Enter the sum:
9
Subset1
1
2
6
Subset2
1
8
finding all the Hamiltonian Paths in a graph. Following images explains the idea
behind Hamiltonian Path more clearly.
Graph shown in Fig.1 does not contain any Hamiltonian Path. Graph shown in
Fig. 2 contains two Hamiltonian Paths which are highlighted in Fig. 3 and Fig. 4
0-1-3-2
2-3-1-0
2. Pseudocode:
function check_all_permutations(adj[][], n)
{
for i = 0 to n
p[i]=i
while next permutation is possible
valid = true
for i = 0 to n-1
if adj[p[i]][p[i+1]] == false
valid = false
break
if valid == true
return true
p = get_next_permutation(p)
return false
}
bool valid=true;
for(int i=0; i<v.size()-1; i++){
if(adj[v[i]][v[i+1]] == false){
valid=false;
break;
}
}
if(valid)
return true;
}while(next_permutation(v.begin(), v.end()));
return false;
}
Time complexity of the above method can be easily derived. For a graph having
N vertices it visits all the permutations of the vertices, i.e. N! iterations and in
each of those iterations it traverses the permutation to see if adjacent vertices
are connected or not i.e N iterations, so the complexity is O( N * N! ).
Program 12
package hamiltonian;
public class Hamiltonian
{
final int V = 5;
int path[];
/* A utility function to check if the vertex v can be added at index 'pos'in the
Hamiltonian
Cycle constructed so far (stored in 'path[]') */
{
/* Check if this vertex is an adjacent vertex of the previously added vertex.
*/
if (graph[path[pos - 1]][v] == 0)
return false;
/* Check if the vertex has already been included.This step can be optimized
by creating
an arrayof size V */
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
return true;
}
/* A recursive utility function to solve hamiltonian cycle problem */
boolean hamCycleUtil(int graph[][], int path[], int pos)
{
/* base case: If all vertices are included in Hamiltonian Cycle */
if (pos == V)
{
// And if there is an edge from the last included
// vertex to the first vertex
if (graph[path[pos - 1]][path[0]] == 1)
return true;
else
return false;
}
/* Let us put vertex 0 as the first vertex in the path.If there is a Hamiltonian
Cycle,
then the path can be started from any point of the cycle as the graph is
undirected */
path[0] = 0;
if (hamCycleUtil(graph, path, 1) == false)
{
//System.out.println("\nSolution does not exist");
return 0;
}
printSolution(path);
return 1;
}
|/ \|
(3) (4) */r
int graph2[][] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
};
// Print the solution
hamiltonian.hamCycle(graph2);
}
}
Output:
Solution Exists: Following is one Hamiltonian Cycle
0 1 2 4 3 0