design and analysis of algorithm laboratory …expt. no. name of the experiment 6 implement in java,...
TRANSCRIPT
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering and
Technology, Vijayapur-586 103
Department of Computer Science and Engineering
DESIGN AND ANALYSIS OF ALGORITHM
LABORATORY MANUAL
(15CSL47)
DESIGN AND ANALYSIS OF ALGORITHM LABORATORY
[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2016 -2017)
SEMESTER – IV
Subject Code 15CSL47 IA Marks 20
No. 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.
Laboratory Experiments
Expt.
No. Name of the Experiment
1 A. Create a Java class called Student with the following details as variables within it.
USN, Name, Branch, Phone
Write a Java program to create n Student 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
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.
Expt.
No. Name of the Experiment
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.
Course Outcomes: The students should be able to:
1. Design and implement object-oriented concepts-operator overloading, constructor,
destructors, virtual functions and templates.
2. Analyze and compare the asymptotic behaviors of functions obtained by elementary
composition of polynomials, exponentials and logarithmic functions.
3. Design and implement different sorting algorithms using different algorithm design
techniques.
4. Design and implement greedy and dynamic approach.
5. Design and implement different graph algorithms to solve different problems.
6. Design and implement branch and bound technique algorithms and backtracking
algorithms.
Graduate Attributes
Engineering Knowledge
Problem Analysis
Modern Tool Usage
Conduct Investigations of Complex Problems
Design/Development of Solutions
Conduction of Practical Examination:
All laboratory experiments (Twelve problems) are to be included for practical examination.
Students are allowed to pick one experiment from the lot.
To generate the data set use random number generator function.
Strictly follow the instructions as printed on the cover page of answer script for breakup of
marks
Marks distribution: Procedure + Conduction + Viva: 20 + 50 + 10 (80).
Change of experiment is allowed only once and marks allotted to the procedure
1. A. Create a Java class called Student with the following details as variables within it.
USN, Name, Branch, Phone
Write a Java program to create n Student objects and print the USN, Name, Branch,
and Phone of these objects with suitable headings.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
class student{
protected String USN;
protected String name;
protected String branch;
protected String phone;
Scanner input=new Scanner(System.in);
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
/* To Read Student Details */
protected void read() throws IOException
{
System.out.println("Enter Proper USN:");
USN=input.next(); //Read Complete String token Withoutspace
System.out.println("Enter Full Name:");
name=in.readLine(); // Read Full Name with Space
System.out.println("Enter Phone Number");
phone=input.next();
System.out.println("Enter Branch");
branch=in.readLine();
} // Read as Line
/** Display Student Details **/
protected void display()
{
System.out.println("\t"+USN+"\t\t"+name+"\t\t"+branch+"\t"+phone);
}
}
/**Main class **/
public class Lab1A
{
static int n;
static Scanner in=new Scanner(System.in);
public static void main(String args[ ])throws IOException
{
System.out.println("Enter the number of students to be read");
n=in.nextInt();
student s[ ]=new student[n];
for(int i=0;i<n;i++)
{
System.out.println("Please enter student"+(i+1)+"record");
s[i]=new student();
s[i].read();
}
System.out.println("***************STUDENT DETAILS**************");
System.out.println("S.No\tUSN\t\t\tName\t\t\tBranch\tPhone No.");
for(int i=0;i<n;i++)
{
System.out.println((i+1));
s[i].display();
}
System.out.println("********************END*******************");
}
}
1 B. Write a Java program to implement the Stack using arrays. Write Push(), Pop(),
and Display() methods to demonstrate its working.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
class StackDemo {
private static final int capacity = 5;
int arr[] = new int[capacity];
int top = -1;
public void push(int pushedElement) {
if (top < capacity - 1) {
top++;
arr[top] = pushedElement;
System.out.println("Element "+pushedElement+" is pushed into Stack!");
}
else {
System.out.println("Stack Overflow !");
}
}
public void pop() {
if (top >= 0) {
top--;
System.out.println("Pop operation is successfull !");
System.out.print("and popped element is :"+ arr[top+1]);
}
else {
System.out.println("Stack Underflow !");
}
}
public void printElements() {
if (top >= 0) {
System.out.println("Elements in stack :");
for (int i = 0; i <= top; i++) {
System.out.println(arr[i]);
}
}
else{
System.out.println(" Stack is empty");
}
}
}
public class Lab1B {
public static void main(String[] args) {
StackDemo stackDemo = new StackDemo();
Scanner in=new Scanner(System.in);
while(true){
System.out.println("\nEnter Your Choice");
System.out.print("1.PUSH \n2.POP \n3.DISPLAY \n");
int Choice=in.nextInt();
switch(Choice)
{
case 1: System.out.println("Enter Number to be pushed:-");
int Number =in.nextInt();
stackDemo.push(Number);
break;
case 2: stackDemo.pop();
break;
case 3: stackDemo.printElements();
break;
default:System.out.println("Invalid Choice");
}
}
}
}
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.
import java.io.BufferedReader;
import java.io.*;
import java.util.Scanner;
/**This is Super Class **/
class staff
{
protected String name;
protected int staffid;
protected int salary;
protected String phone;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Scanner input=new Scanner(System.in);
/* To Read Student Details */
protected void read() throws IOException
{
System.out.println("Enter Staff ID:");
staffid=input.nextInt();
System.out.println("Enter Staff Name:");
name=in.readLine();
System.out.println("Enter Staff Phone Number");
phone=in.readLine();
System.out.println("Enter Staff Salary");
salary=input.nextInt();
}
}
/** SUBCLASS TEACHING INHERITED BY staff Class **/
class teaching extends staff
{
protected String domain;
protected String publisher;
protected void read()throws IOException
{
super.read();
System.out.println("Enter the Staff Domain");
domain=in.readLine();
System.out.println("Enter the Publisher");
publisher=in.readLine();
}
/** Display teaching staff details **/
protected void display()
{
System.out.println(staffid+"\t"+name+"\t\t"+phone+"\t"+salary+"\t"+domain+"\t"+publisher)
;
}
}
/* SUBCLASS TECHNICAL INHERITED BY staff Class **/
class technical extends staff
{
int n;
protected String[] skils;
protected void read()throws IOException
{
super.read();
System.out.println("Enter the subject skills He/She Has");
n=input.nextInt();
skils=new String[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter Skills"+(i+1));
skils[i]=input.next();
}
}
void display()
{
System.out.println(staffid+"\t"+name+"\t\t"+phone+"\t"+salary+"\t");
for(int j=0;j<skils.length;j++)
System.out.println(skils[j]+",");
System.out.println(" ");
}
}
/**SUBCLASS OF STAFF **/
class contractor extends staff
{
protected int period;
protected void read() throws IOException
{
super.read();
System.out.println("How many years of Contract");
period=input.nextInt();
}
void display()
{
System.out.println(staffid+"\t"+name+"\t\t"+phone+"\t"+salary+"\t"+period);
}
}
public class Lab2A
{
static int m,n,o;
static Scanner input=new Scanner(System.in);
public static void main(String args[])throws IOException
{
teaching[] s;
technical[] t;
contractor[] c;
/** READING **/
System.out.println("\n***** Read Teaching Staff Details ****");
System.out.println("Enter the number of Teaching staff");
m=input.nextInt();
s=new teaching[m];
for(int i=0;i<m;i++)
{
s[i]=new teaching();
System.out.println("------------------- Enter Teaching Staff"+(i+1)+"Details------------------");
s[i].read();
}
System.out.println("\n******* Read Technical Staff Details *******");
System.out.println("Enter the number of Technical staff");
n=input.nextInt();
t=new technical[n];
for(int i=0;i<n;i++)
{
t[i]=new technical();
System.out.println("------------------- Enter Technical Staff"+(i+1)+"Details------------------");
t[i].read();
}
System.out.println("\n****** Read Contactor Staff Details ******");
System.out.println("Enter the number of Contractor staff");
o=input.nextInt();
c=new contractor[o];
for(int i=0;i<o;i++)
{
c[i]=new contractor();
System.out.println("------------------- Enter contractor Staff"+(i+1)+"Details------------------");
c[i].read();
}
/**DISPLAY**/
System.out.println("\n\t*****TEACHING STAFF ******\t");
System.out.println("SID\tNAME\t\tPHONE NO\tSALARY\tDOMAIN\tPUBLISHER");
System.out.println("---------------------------------------------------------------------------");
for(int i=0;i<m;i++)
{
s[i].display();
}
System.out.println("\n\t****************TECHNICAL STAFF *********\t");
System.out.println("SID\tNAME\t\tPHONE NO\tSALARY\tSKILLS");
System.out.println("---------------------------------------------------------------------------");
for(int i=0;i<n;i++)
{
t[i].display();
}
System.out.println("\n\t*************CONTRACTOR STAFF ******************\t");
System.out.println("SID\tNAME\t\tPHONE NO\tSALARY\tYEAR OF CONTRACT");
System.out.println("---------------------------------------------------------------------------");
for(int i=0;i<o;i++)
{
c[i].display();
}
}
}
2 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 “/”.
import java.util.Scanner;
import java.util.StringTokenizer;
class Customer{
private String name;
private String date_of_birth;
public Customer(String name, String date_of_birth) {
super();
this.name = name;
this.date_of_birth = date_of_birth;
}
public Customer (){
}
public void readData(String name, String date_of_birth){
this.name = name;
this.date_of_birth = date_of_birth;
}
public void displayData(){
StringTokenizer st=new
StringTokenizer(this.date_of_birth,"/");
System.out.print(this.name+",");
while(st.hasMoreTokens()){
System.out.print(st.nextToken()+" ");
}
}
}
public class Lab2B {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter Name :-");
String name=in.nextLine();
System.out.println("Enter Date of birth:-");
String date=in.next();
Customer customer=new Customer();
customer.readData(name, date);
customer.displayData();
}
}
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.
import java.util.Scanner;
class MyException extends Exception
{
public String toString() {
return "Denominator is 0! Division by zero ERROR";
}
}
class Compute
{
private int a,b;
public Compute(int a, int b) {
super();
this.a = a;
this.b = b;
}
public void compute_a_by_b() {
try {
if (this.b != 0) {
System.out.println("Result a/b="+(float)1.0*this.a/this.b);
}
else throw new MyException();
} catch (MyException e) {
System.out.println("Error !!!!: " + e);
}
}
}
public class Lab3A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a :-");
int a = in.nextInt();
System.out.print("Enter b:-");
int b = in.nextInt();
Compute compute = new Compute(a, b);
compute.compute_a_by_b();
}
}
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.
import java.util.Random;
class SquareThread implements Runnable
{
int x;
SquareThread(int x)
{
this.x = x;
}
public void run() {
System.out.println("Thread Name:Square Thread and Square of " + x + " is: " + x * x);
}
}
class CubeThread implements Runnable
{
int x;
CubeThread(int x)
{
this.x = x;
}
public void run( )
{
System.out.println("Thread Name:Cube Thread and Cube of " + x + " is: " + x * x * x);
}
}
class RandomThread implements Runnable {
Random r;
Thread t2, t3;
public void run() {
int num;
r = new Random();
try {
while (true) {
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
t2 = new Thread(new SquareThread(num));
t2.start();
t3 = new Thread(new CubeThread(num));
t3.start();
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
} catch (Exception ex)
{
System.out.println("Interrupted Exception");
}
}
}
public class MainThread
{
public static void main(String[] args)
{
RandomThread thread_obj = new RandomThread();
Thread t1 = new Thread(thread_obj);
t1.start();
}
}
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;
public class QuickSort
{
private int[] a;
void input(){
Scanner sc = new Scanner(System.in);
Random rm = new Random();
System.out.print("Enter the total numbers: ");
int n = sc.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = rm.nextInt(1000); // Generates random numbers 0-999
}
}
void display( )
{
for (int i : a)
{
System.out.print(i + " ");
}
}
void sort( )
{
quicksort(0, a.length - 1);
}
void quicksort(int left, int right)
{
if (left < right)
{
int s = partition(left, right);
quicksort(left, s - 1);
quicksort(s + 1, right);
}
}
int partition(int left, int right)
{
int pivot = a[left];
int i = left;
int j = right + 1;
do
{
do
{
++i;
} while (i < right && a[i] < pivot);
do
{
--j;
} while (a[j] > pivot);
swap(i, j);
} while (i < j);
swap(i, j); // undo last swap
swap(left, j);
return j;
}
private void swap(int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String args[ ])
{
QuickSort sorter = new QuickSort();
sorter.input();
System.out.println("Array before sorting");
sorter.display();
long startTime = System.nanoTime();
sorter.sort();
long endTime = System.nanoTime();
double duration = (endTime - startTime) / 1000000.00;
//divide by 1000000 to get milliseconds.
System.out.println("\nArray After sorting");
sorter.display();
System.out.println("\nTime for sorting is " + duration + " milli seconds");
}
}
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.Random;
import java.util.Scanner;
public class MergeSort
{
private int[] a;
void input( )
{
Scanner sc = new Scanner(System.in);
Random rm = new Random();
System.out.print("Enter the total numbers: ");
int n = sc.nextInt();
a = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = rm.nextInt(1000); // Generates random numbers 0-999
} //rm.nextInt() can also be used
}
void display( )
{
for (int i : a)
{
System.out.print(i + " ");
}
}
void sort( )
{
mergesort(0, a.length - 1);
}
void mergesort(int left, int right)
{
int mid;
if (left < right) {
mid = (left + right) / 2;
mergesort(left, mid);
mergesort(mid + 1, right);
merge(left, mid, right);
}
}
void merge(int left, int mid, int right)
{
int temp[] = new int[a.length];
for (int i = left; i <= right; i++)
{
temp[i] = a[i];
}
int i = left;
int j = mid + 1;
int k = left;
while (i <= mid && j <= right)
{
if (temp[i] <= temp[j])
{
a[k++] = temp[i++];
}
else
{
a[k++] = temp[j++];
}
}
while (i <= mid)
{
a[k++] = temp[i++];
}
while (j <= right)
{
a[k++] = temp[j++];
}
}
public static void main(String args[ ])
{
MergeSort sorter = new MergeSort( );
sorter.input( );
System.out.println("Array before sorting");
sorter.display( );
long startTime = System.nanoTime( );
sorter.sort( );
long endTime = System.nanoTime( );
double duration = (endTime - startTime) / 1000000.00; //divide by 1000000 to get
milliseconds.
System.out.println("\nArray After sorting");
sorter.display();
System.out.println("\nTime for sorting is " + duration + " milli seconds");
}
}
6. Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming
method (b) Greedy method.
import java.util.Scanner;
public class Lab6A
{
public static void main(String[] args)
{
int v[][]=new int[10][10], w[]=new int[10], p[]=new int[10];
Scanner in = new Scanner(System.in);
int i, j;
System.out.println("************* KNAPSACK PROBLEM ***********");
System.out.println("Enter the total number of items: ");
int n = in.nextInt();
System.out.println("Enter the weight of each item: ");
for(i=1;i<=n;i++)
w[i] = in.nextInt();
System.out.println("Enter the profit of each item: ");
for(i=1;i<=n;i++)
p[i] = in.nextInt();
System.out.println("Enter the knapsack capacity: ");
int m= in.nextInt();
displayinfo(m,n,w,p);
knapsack(m,n,w,p,v);
System.out.println("The contents of the knapsack table are");
for(i=0; i<=n; i++)
{
for(j=0; j<=m; j++)
{
System.out.print(v[i][j]+" " );
}
System.out.println();
}
optimal(m,n,w,v); //call optimal function
}
static void displayinfo(int m,int n,int w[],int p[])
{
System.out.println("Entered information about knapsack problem are");
System.out.println("ITEM\tWEIGHT\tPROFIT");
for(int i=1; i<=n; i++)
System.out.println(i+"\t"+w[i]+"\t"+p[i]);
System.out.println("Capacity = "+m);
}
static void knapsack(int m,int n,int w[ ],int p[ ],int v[ ][ ])
{
for(int i=0; i<=n; i++)
{
for(int j=0; j<=m; j++)
{
if(i==0 ||j==0)
v[i][j]=0;
else if(j < w[i])
v[i][j]=v[i-1][j];
else
v[i][j]=max(v[i-1][j], v[i-1][j-w[i]]+p[i]);
}
}
}
private static int max(int i, int j) {
if(i>j)
return i;
else return j;
}
static void optimal(int m,int n,int w[],int v[][]){
int i = n, j = m, item=0;
int x[]=new int[10];
while( i != 0 && j != 0)
{
if(v[i][j] != v[i-1][j])
{
x[i] = 1;
j = j-w[i];
}
i = i-1;
}
System.out.println("Optimal solution is :"+ v[n][m]);
System.out.println("Selected items are: ");
for(i=1; i<= n;i++)
if(x[i] == 1){
System.out.print(i+" ");
item=1;
}
if(item == 0)
System.out.println("NIL\t Sorry ! No item can be placed in Knapsack");
System.out.println("\n********* *********************** *************");
}
}
6 B Implement in Java, the 0/1 Knapsack problem using Greedy method.
import java.util.Scanner;
public class Lab6B
{
public static void main(String[] args)
{
float w[]=new float[10],p[]=new float[10];
float ratio[]=new float[10];
Scanner in = new Scanner(System.in);
int i;
System.out.println("********* KNAPSACK PROBLEM *******");
System.out.println("Enter the total number of items: ");
int n = in.nextInt();
System.out.println("Enter the weight of each item: ");
for(i=1;i<=n;i++)
w[i] = in.nextFloat();
System.out.println("Enter the profit of each item: ");
for(i=1;i<=n;i++)
p[i] = in.nextFloat();
System.out.println("Enter the knapsack capacity: ");
int m= in.nextInt();
for(i=1;i<=n;i++)
ratio[i]=p[i]/w[i];
System.out.println("Information about knapsack problem are");
displayinfo(n,w,p,ratio);
System.out.println("Capacity = "+m);
sortArray(n,ratio,w,p);
System.out.println("\nDetails after sorting items based on Profit/Weight ratio in descending
order: ");
displayinfo(n,w,p,ratio);
knapsack(m,n,w,p);
System.out.println("*************");
}
static void sortArray(int n,float ratio[],float w[],float p[])
{
int i,j;
for(i=1; i<=n; i++)
for(j=1; j<=n-i; j++)
{
if(ratio[j]<ratio[j+1])
{
float temp=ratio[j];
ratio[j]=ratio[j+1];
ratio[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;
}
}
}
static void displayinfo(int n,float w[],float p[],float ratio[])
{
System.out.println("ITEM\tWEIGHT\tPROFIT\tRATIO(PROFIT/WEIGHT)");
for(int i=1; i<=n; i++)
System.out.println(i+"\t"+w[i]+"\t"+p[i]+"\t"+ratio[i]);
}
static void knapsack(int u,int n,float w[],float p[])
{
float x[]=new float[10],tp=0;
int i;
for(i=1; i<=n; i++)
x[i]=0;
for(i=1; i<=n; i++)
{
if(w[i]>u)
break;
else
{
x[i]=1;
tp=tp+p[i];
u=(int) (u-w[i]);
}
}
if(i<n)
x[i]=u/w[i];
tp=tp+(x[i]*p[i]);
System.out.println("\nThe result is = ");
for(i=1; i<=n; i++)
System.out.print("\t"+x[i]);
System.out.println("\nMaximum profit is = "+tp);
}
}
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 Lab7
{
public static void main(String[] args)
{
int i, j;
int dist[ ]=new int[10], visited[ ]=new int[10];
int cost[ ][ ]=new int[10][10], path[ ]=new int[10];
Scanner in = new Scanner(System.in);
System.out.println("**** DIJKSTRA'S ALGORITHM ******");
System.out.println("Enter the number of nodes: ");
int n = in.nextInt();
System.out.println("Enter the cost matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cost[i][j] = in.nextInt();
System.out.println("The entered cost matrix is");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(cost[i][j]+"\t");
}
System.out.println();
}
System.out.println("Enter the source vertex: ");
int sv = in.nextInt();
dij(cost,dist,sv,n,path,visited);
printpath(sv,n,dist,path,visited );
System.out.println("\n********* *************** *********");
}
static void dij(int cost[][],int dist[],int sv,int n,int path[],int visited[])
{
int count = 2,min,v=0;
for(int i=1; i<=n; i++)
{
visited[i]=0;
dist[i] = cost[sv][i];
if(cost[sv][i] == 999)
path[i] = 0;
else
path[i] = sv;
}
visited[sv]=1;
while(count<=n)
{
min = 999;
for(int w=1; w<=n; w++)
if((dist[w]< min) && (visited[w]==0))
{
min = dist[w];
v = w;
}
visited[v] = 1;
count++;
for(int w=1; w<=n; w++)
{
if((dist[w]) >(dist[v] + cost[v][w]))
{
dist[w] = dist[v] + cost[v][w];
path[w] = v;
}
}
}
}
static void printpath(int sv,int n,int dist[ ],int path[ ], int visited[ ])
{
for(int w=1; w<=n; w++)
{
if(visited[w] == 1 && w != sv)
{
System.out.println("The shortest distance between ");
System.out.println(sv+ "->="+w+" is :"+ dist[w]);
int t=path[w];
System.out.println("The path is:");
System.out.print(" "+w);
while(t != sv)
{
System.out.print("<--"+t);
t=path[t];
}
System.out.print("<--"+sv);
}
}
}
}
8. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal'salgorithm. Use Union-Find algorithms in your program.
import java.util.Scanner;
public class Lab8A
{
public static void main(String[] args)
{
int cost[ ][ ]=new int[10][10];
int i, j,mincost=0;
Scanner in = new Scanner(System.in);
System.out.println("********* KRUSKAL'S ALGORITHM *******");
System.out.println("Enter the number of nodes: ");
int n = in.nextInt();
System.out.println("Enter the cost matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cost[i][j] = in.nextInt();
}
}
System.out.println("The entered cost matrix is");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(cost[i][j]+"\t");
}
System.out.println();
}
mincost=kruskals(n,mincost,cost);
System.out.println("The minimum spanning tree cost is: ");
System.out.println(mincost);
System.out.println("********* ****************** **********");
}
static int kruskals(int n,int mincost,int cost[][] )
{
int ne = 1,a=0,u=0,b=0,v=0,min;
int parent[]=new int[10];
while(ne < n)
{
min=999;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
if(cost[i][j] < min)
{
min = cost[i][j];
a=u=i;
b=v=j;
}
}
}
while(parent[u]>0)
u = parent[u];
while(parent[v]>0)
v = parent[v];
if(u != v)
{
System.out.println((ne++)+">minimum edge is :");
System.out.println("("+a+","+b+") and its cost is:"+min);
mincost += min;
parent[v] = u;
}
cost[a][b] = cost[b][a] = 999;
}
return mincost;
}
}
9. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Prim's algorithm.
import java.util.Scanner;
public class Lab8B
{
public static void main(String[] args)
{
int cost[][]=new int[10][10];
int i, j, mincost = 0;
Scanner in = new Scanner(System.in);
System.out.println("********* PRIMS ALGORITHM *********");
System.out.println("Enter the number of nodes");
int n = in.nextInt();
System.out.println("Enter the cost matrix");
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
cost[i][j] = in.nextInt();
}
}
System.out.println("The entered cost matrix is");
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
System.out.print(cost[i][j]+"\t");
}
System.out.println();
}
System.out.println("Minimum Spanning Tree Edges and costs are");
mincost=prims(cost,n,mincost);
System.out.println("The minimum spanning tree cost is");
System.out.println (+mincost);
System.out.println("******* ********************* *******");
}
static int prims(int cost[][],int n,int mincost)
{
int nearV[]=new int[10],t[][]=new int[10][3],u = 0,i,j,k;
for(i=2; i<=n; i++)
nearV[i]=1;
nearV[1]=0;
for(i=1; i<n; i++)
{
int min=999;
for(j=1;j<=n;j++)
{
if(nearV[j]!=0 && cost[j][nearV[j]]<min)
{
min=cost[j][nearV[j]];
u=j;
}
}
t[i][1] = u;
t[i][2] = nearV[u];
mincost += min;
nearV[u] = 0;
for(k=1; k<=n; k++)
{
if(nearV[k] != 0 && cost[k][nearV[k]] > cost[k][u])
nearV[k] = u;
}
System.out.print(i+") Minimum edge is ("+t[i][1]);
System.out.println(","+t[i][2]+") and its cost is :"+min);
}
return mincost;
}
}
10. Write Java programs to
a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
import java.util.Scanner;
public class Floyds
{
static int[ ][ ] dist;
static int n;
static void floyds( )
{
int i, j, k;
for (k = 1; k <= n; k++) // record the lengths of shortest path
{
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
}
static int min(int a, int b)
{
if (a < b)
{
return a;
} else
{
return b;
}
}
public static void main(String[ ] args)
{
int i, j;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of vertices");
n = sc.nextInt();
dist = new int[n + 1][n + 1];
System.out.println("Enter the adjacency matrix (999 for no edge)");
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
dist[i][j] = sc.nextInt( );
}
}
floyds( );
System.out.println("All pairs shortest path matrix is");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
System.out.print(dist[i][j] + "\t");
}
System.out.println();
}
}
}
10 b) Implement Travelling Sales Person problem using Dynamic programming.
import java.util.Scanner;
public class Lab10B
{
public static void 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 cities: ");
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 entered 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 = tspdp(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("******* ************* ***************");
}
static int tspdp(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=tspdp(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;
}
}
11. Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n
positive integers whose SUM is equal to a given positive integer d. For example, if S ={1,
2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message,
if the given problem instance doesn't have a solution.
import java.util.Scanner;
public class SumOfSubset
{
static int[] set, x;
static int d, n;
static void sumofsub(int s, int k) {
int i;
x[k] = 1; //generate left child
if (s + set[k] == d) {
System.out.print("{");
for (i = 1; i <= n; i++) {
if (x[i] == 1) //subset found
{
System.out.print( set[i] + ",");
}
}
System.out.println("\b}");
} else {
if (s + set[k] < d && k + 1 <= n) //with s[k]
{
sumofsub(s + set[k], k + 1); //Generate right child
x[k + 1] = 0;
}
if (k + 1 <= n && s + set[k + 1] <= d )//without s[k]
{
x[k] = 0;
sumofsub(s, k + 1);
x[k + 1] = 0;
}
}
}
public static void main(String[] args) {
int sum = 0, i, flag=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of the set");
n = sc.nextInt();
set = new int [n+1];
x = new int [n+1];
System.out.println("Enter set elements in increasing order");
for (i = 1; i <= n; i++) {
set[i] = sc.nextInt();
}
System.out.println("Enter maximum limit for sum");
d = sc.nextInt();
for (i = 1; i <= n; i++)
{
sum = sum + set[i];
}
if (sum < d||set[1]> d)
{
System.out.println("No subset possible");
}
else
{
System.out.println("The subsets with sum of elements = " + d + " are");
sumofsub(0, 1);
}
}
}
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;
import java.util.Arrays;
public class HamiltonianCycle /** Class HamiltonianCycle **/
{
private int V, pathCount;
private int[] path;
private int[][] graph;
public void findHamiltonianCycle(int[][] g) /** Function to find cycle **/
{
V = g.length;
path = new int[V];
Arrays.fill(path, -1);
graph = g;
try
{
path[0] = 0; pathCount = 1;
solve(0);
System.out.println("No solution");
}
catch (Exception e)
{
System.out.println(e.getMessage());
display();
}
}
/** function to find paths recursively **/
public void solve(int vertex) throws Exception
{
/** solution **/
if (graph[vertex][0] == 1 && pathCount == V)
throw new Exception("Solution found");
/** all vertices selected but last vertex not linked to 0 **/
if (pathCount == V)
return;
for (int v = 0; v < V; v++)
{
/** if connected **/
if (graph[vertex][v] == 1 )
{
/** add to path **/
path[pathCount++] = v;
/** remove connection **/
graph[vertex][v] = 0;
graph[v][vertex] = 0;
/** if vertex not already selected solve recursively **/
if (!isPresent(v))
solve(v);
graph[vertex][v] = 1; /** restore connection **/
graph[v][vertex] = 1;
path[--pathCount] = -1; /** remove path **/
}
}
}
public boolean isPresent(int v) /** function to check if path is already selected **/
{
for (int i = 0; i < pathCount - 1; i++)
if (path[i] == v)
return true;
return false;
}
public void display() /** display solution **/
{
System.out.print("\nPath : ");
for (int i = 0; i <= V; i++)
System.out.print(path[i % V] +" ");
System.out.println();
}
public static void main (String[] args) /** Main function **/
{
Scanner sc = new Scanner(System.in);
HamiltonianCycle hc = new HamiltonianCycle();
System.out.println("Enter number of vertices\n"); /** Accept number of vertices **/
int V = sc.nextInt();
System.out.println("\nEnter matrix\n"); /** get graph **/
int[][] graph = new int[V][V];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph[i][j] = sc.nextInt();
hc.findHamiltonianCycle(graph);
}
}