0% found this document useful (0 votes)
29 views37 pages

Programs

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

Programs

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

Govenment Enginerring College Hassan

Java and ADA Programs for lab


1
A.Create a Java class called Studentwith 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
Phoneof these objects with suitable headings.

Program
import java.util.Scanner;
public class Student
{
String USN;
String Name;
String Branch;
long Phone;
void InsertRecord(String usn, String name,String branch, long phone)
{
USN=usn;
Name=name;
Branch=branch;
Phone=phone;
}
void displayRecord()
{
System.out.println(USN+" "+Name+" "+Branch+" "+Phone);
}
public static void main(String args[])
{
Student s[]=new Student[100];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of students ");
int n=sc.nextInt();
for(int i=0;i<n;i++)
s[i]=new Student();
for(int j=0;j<n;j++)
{
System.out.println("Enter the USN,Name,Branch,Phone");
String USN=sc.next();
String Name=sc.next();
String Branch=sc.next();
long Phone=sc.nextLong();
s[j].InsertRecord(USN,Name,Branch,Phone);
}
for(int m=0;m<n;m++)
{

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

s[m].displayRecord();
}
}
}

output

Enter the number of students


3
Enter the USN,Name,Branch,Phone
4GH15CS001
Amith
cse
1234567810
Enter the USN,Name,Branch,Phone
4GH15CS002
Anagha
cse
1234567811
Enter the USN,Name,Branch,Phone
4GH15CS003
Ananya
cse
1234567812
4GH15CS001 Amith cse 1234567810
4GH15CS002 Anagha cse 1234567811
4GH15CS003 Ananya cse 1234567812

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

1.B
Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.

Program

import java.util.Scanner;
public class Stack
{
final int max=100;
int s[]=new int[max];
int top=-1;
void push(int element)
{
if(top>=max-1)
System.out.println("Stack overflow");
else
s[++top]=element;
}
int pop()
{
int z=0;
if(top==-1)
System.out.println("Stack underflow");
else
z=s[top--];
return z;
}
void display()
{
if(top==-1)
System.out.println("Stack empty");
else
{
for(int i=top;i>-1;i--)
System.out.println(s[i]+" ");
}
}
public static void main(String args[])
{
int q=1;
Stack m= new Stack();
Scanner sc=new Scanner(System.in);
while(q!=0)
{
System.out.println("Enter your
choice\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
int ch=sc.nextInt();

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

switch(ch)
{
case 1:
System.out.println("Enter the element to be pushed");
int element=sc.nextInt();
m.push(element);
break;
case 2:
int pop_element;
pop_element=m.pop();
System.out.println("The popped element is: ");
System.out.println(pop_element+" ");
break;
case 3:
System.out.println("Elements is the stack are");
m.display();
break;
case 4:
q=0;
return;
}
}
}
}

output
Enter your choice
1.Push
2.Pop
3.Display
4.Exit

1
Enter the element to be pushed
2
Enter your choice
1.Push
2.Pop
3.Display
4.Exit

1
Enter the element to be pushed
3
Enter your choice
1.Push
2.Pop

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

3.Display
4.Exit

1
Enter the element to be pushed
4
Enter your choice
1.Push
2.Pop
3.Display
4.Exit

1
Enter the element to be pushed
5
Enter your choice
1.Push
2.Pop
3.Display
4.Exit

3
Elements is the stack are
5
4
3
2
Enter your choice
1.Push
2.Pop
3.Display
4.Exit

2
The popped element is:
5
Enter your choice
1.Push
2.Pop
3.Display
4.Exit

2
The popped element is:
4
Enter your choice
1.Push
2.Pop

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

3.Display
4.Exit

2
The popped element is:
3
Enter your choice
1.Push
2.Pop
3.Display
4.Exit

2
The popped element is:
2
Enter your choice
1.Push
2.Pop
3.Display
4.Exit

2
Stack underflow
The popped element is:
0
Enter your choice
1.Push
2.Pop
3.Display
4.Exit

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

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

Program
staff.java

class staff
{
int staff_id,phone,salary;
String Name;
public staff(int id, int number,int Salary,String name)
{
staff_id=id;
phone=number;
salary=Salary;
Name=name;
}
void display()
{
System.out.println("-----------------");
System.out.println("Staff ID:"+" "+staff_id);
System.out.println("Staff phone number:"+" "+phone);
System.out.println("Staff salary:"+" "+salary);
System.out.println("Staff name:"+" "+Name);
}
}
class teaching extends staff
{
String domain;
int no_of_publications;
public teaching(int id,int number,int salary,String name,String d,int nop)
{
super(id,number,salary,name);
domain=d;
no_of_publications=nop;
}
void display()
{
System.out.println("Teaching staff details");
super.display();
System.out.println("Domain:"+" "+domain);
System.out.println("No of publications:"+" "+no_of_publications);
}
}
class technical extends staff

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

{
String skills;
public technical(int id,int number,int salary,String name,String skl)
{
super(id,number,salary,name);
skills=skl;
}
void tecdisplay()
{
System.out.println("------------");
System.out.println("Technical staff details");
super.display();
System.out.println("Skills:"+" "+skills);
}
}
class contract extends staff
{
int period;
public contract(int id,int number,int salary,String name,int prd)
{
super(id,number,salary,name);
period=prd;
}
void cdisplay()
{
System.out.println("-----------");
System.out.println("Contract staff details");
super.display();
System.out.println("Contract period:"+" "+period+"years");
}
}

multilevel.java
public class multilevel
{
public static void main(String args[])
{
teaching t1=new teaching(1,990023,25000,"Ram","ISE",6);
teaching t2=new teaching(2,889123,30000,"John","CSE",6);
teaching t3=new teaching(3,778087,32000,"Jobs","CSE",6);
t1.display();
t2.display();
t3.display();
technical te1=new technical(101,944567,20000,"Jasmine","C");
technical te2=new technical(102,988045,23000,"Stella","C++");

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

technical te3=new technical(103,813776,28000,"Jenni","Java");


te1.tecdisplay();
te2.tecdisplay();
te3.tecdisplay();
contract ct1= new contract(2001,903508,18000,"Arnav",3);
contract ct2=new contract(2002,914589,18000,"mia",2);
contract ct3=new contract(2003,813478,18000,"Xen",3);
ct1.cdisplay();
ct2.cdisplay();
ct3.cdisplay();
}
}
output
Teaching staff details
-----------------
Staff ID: 1
Staff phone number: 990023
Staff salary: 25000
Staff name: Ram
Domain: ISE
No of publications: 6
Teaching staff details
-----------------
Staff ID: 2
Staff phone number: 889123
Staff salary: 30000
Staff name: John
Domain: CSE
No of publications: 6
Teaching staff details
-----------------
Staff ID: 3
Staff phone number: 778087
Staff salary: 32000
Staff name: Jobs
Domain: CSE
No of publications: 6
------------
Technical staff details
-----------------
Staff ID: 101
Staff phone number: 944567
Staff salary: 20000
Staff name: Jasmine
Skills: C
------------
Technical staff details
-----------------

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

Staff ID: 102


Staff phone number: 988045
Staff salary: 23000
Staff name: Stella
Skills: C++
------------
Technical staff details
-----------------
Staff ID: 103
Staff phone number: 813776
Staff salary: 28000
Staff name: Jenni
Skills: Java
-----------
Contract staff details
-----------------
Staff ID: 2001
Staff phone number: 903508
Staff salary: 18000
Staff name: Arnav
Contract period: 3years
-----------
Contract staff details
-----------------
Staff ID: 2002
Staff phone number: 914589
Staff salary: 18000
Staff name: mia
Contract period: 2years
-----------
Contract staff details
-----------------
Staff ID: 2003
Staff phone number: 813478
Staff salary: 18000
Staff name: Xen
Contract period: 3years

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

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 “/”.

Program

import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
class customer
{
String temp;
int dd;
int mm,yyyy;
public void custdetail(String name,String date)
{
StringTokenizer token=new StringTokenizer(date,",/");
temp=token.nextToken();
dd=Integer.parseInt(temp);
temp=token.nextToken();
mm=Integer.parseInt(temp);
temp=token.nextToken();
yyyy=Integer.parseInt(temp);
System.out.println(name+","+dd+","+mm+","+yyyy+" ");
}
}
public class customerdetails
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the name");
String name=s.next();
System.out.println("Enter the date in dd/mm/yyyy,format");
String date= s.next();
customer c=new customer();
c.custdetail(name,date);
}
}
output
Enter the name
boys
Enter the date in dd/mm/yyyy,format
07/12/2016
boys,12,12,2016
3A.

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

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.

Program

import java.util.Scanner;
import java.util.ioException;

public class divisionbyzero


{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
System.out.println("Enter two number:");
double number1=input.nextDouble();
double number2=input.nextDouble();
double quotient=(number1/number2);
System.out.println("The quotient is "+quotient);
if(number2!=0)
{
System.out.println("The value of number1 is "+number1);
System.out.println("The value of number2 is "+number2);
}
else
throw new ArithmeticException("Not Valid");
}
}
output
Enter two number:
23
The quotient is 0.6666666666666666
The value of number1 is 2.0
The value of number2 is 3.0

Enter two number:


20
The quotient is Infinity
Exception in thread "main" java.lang.ArithmeticException: Not Valid
at divisionbyzero.main(divisionbyzero.java:20)

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

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

//squre.java

import java.util.*;
public class square implements Runnable
{
public int x;
public square(int x)
{
this.x=x;
}
public void run()
{
System.out.println("From second thread square of "+x+" is: "+x*x);
}

//cube.java

import java.util.*;
public class cube implements Runnable
{
public int x;
public cube(int x)
{
this.x=x;
}
public void run()
{
System.out.println("From second thread cube of "+x+" is: "+x*x*x);
}

//Firstthreadrandom.java

import java.util.*;
public class Firstthreadrandom extends Thread
{
public void run()
{
int num=0;
Random r=new Random();

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

try
{
for(int i=0;i<5;i++)
{
num=r.nextInt(100);
System.out.println("Main Thread started and generated numbers is: "+num);
Thread t2=new Thread(new square(num));
t2.start();
Thread t3=new Thread(new cube(num));
t3.start();
Thread.sleep(1000);
System.out.println("-------------------------------------------");
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}

//multithreaded.java

import java.util.*;
public class multithreaded
{
public static void main(String args[])
{
Firstthreadrandom FirstThread=new Firstthreadrandom();
Thread t1=new Thread(FirstThread);
t1.start();
}
}

output

Main Thread started and generated numbers is: 15


From second thread square of 15 is: 225
From second thread cube of 15 is: 3375
-------------------------------------------
Main Thread started and generated numbers is: 52
From second thread square of 52 is: 2704
From second thread cube of 52 is: 140608
-------------------------------------------
Main Thread started and generated numbers is: 46
From second thread square of 46 is: 2116
From second thread cube of 46 is: 97336
-------------------------------------------

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

Main Thread started and generated numbers is: 84


From second thread square of 84 is: 7056
From second thread cube of 84 is: 592704
-------------------------------------------
Main Thread started and generated numbers is: 21
From second thread square of 21 is: 441
From second thread cube of 21 is: 9261

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

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.

Program

import java.util.Random;
import java.util.Scanner;
public class quicksort
{
static int max=2000;
int partition(int []a,int low,int high)
{
int p,i,j,temp;
p=a[low];
i=low+1;
j=high;
while(low<high)
{
while(a[i]<=p&&i<high)
i++;
while(a[j]>p)
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
{
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;
}
}
return j;
}
void sort(int []a,int low,int high)
{
if(low<high)
{

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

int s=partition(a,low,high);
sort(a,low,s-1);
sort(a,s+1,high);
}
}
public static void main(String []args)
{
int []a;
int i;
System.out.println("Enter the array size");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();

a=new int[max];
Random generator=new Random();
for(i=0;i<n;i++)
a[i]=generator.nextInt(20);
System.out.println("Array before sorting ");
for(i=0;i<n;i++)
System.out.println(a[i]+" ");
long startTime=System.nanoTime();
quicksort m=new quicksort();
m.sort(a,0,n-1);
long stopTime=System.nanoTime();
long elapseTime=(stopTime-startTime);
System.out.println("Time taken to sort array is: "+elapseTime+" nanoseconds");
System.out.println("Sorted array is:");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}

output

Enter the array size


20
Array before sorting
9 13 13 13 4 18 4 19 10 6 2 7 17 2 17 11 0 9 18 12
Time taken to sort array is: 22795 nanoseconds
Sorted array is:
0 2 2 4 4 6 7 9 9 10 11 12 13 13 13 17 17 18 18 19

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

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.

Program

//remove comment if needed for random number generator


import java.util.Random;
import java.util.Scanner;
public class mergesort
{
static int max=50000;
void merge(int []array,int low,int mid,int high)
{
int i=low;
int j=mid+1;
int k=low;
int resarray[];
resarray=new int[max];
while(i<=mid&&j<=high)
{
if(array[i]<array[j])
{
resarray[k]=array[i];
i++;
k++;
}
else
{
resarray[k]=array[j];
j++;
k++;
}
}
while(i<=mid)
resarray[k++]=array[i++];
while(j<=high)
resarray[k++]=array[j++];
for(int m=low;m<=high;m++)
array[m]=resarray[m];
}
void sort(int []array,int low,int high)
{

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

if(low<high)
{
int mid=(low+high)/2;
sort(array,low,mid);
sort(array,mid+1,high);
merge(array,low,mid,high);
}
}
public static void main(String args[])
{
int array[];
int i;
System.out.println("Enter the size of an array");
Scanner sc =new Scanner(System.in);
int n=sc.nextInt();
array=new int[max];
/*System.out.println("Enter the array");
for(i=0;i<n;i++)
array[i]=sc.nextInt();*/
/**/Random generator=new Random();
for(i=0;i<n;i++)
array[i]=generator.nextInt(10000);/**/
System.out.println("Array before sorting\n");
for(i=0;i<n;i++)
System.out.println(array[i]+" ");
long startTime=System.nanoTime();
mergesort m=new mergesort();
m.sort(array,0,n-1);
long stopTime=System.nanoTime();
long elapseTime=(stopTime-startTime);
System.out.println("Time taken to sort array is"+elapseTime+"nanoseconds");
System.out.println("Sorted array is");
for(i=0;i<n;i++)
System.out.println(array[i]+" ");
System.out.println("Time taken to sort array is"+elapseTime+"nanoseconds");
}
}
output
Enter the size of an array
20
Array before sorting
3018 7781 9067 6515 2830 2620 8019 1806 3027 4418 5700 8431 2368 9810 5716 5627 1044
9643 5330 3537
Time taken to sort array is861826nanoseconds
Sorted array is
1044 1806 2368 2620 2830 3018 3027 3537 4418 5330 5627 5700 5716 6515 7781 8019 8431
9067 9643 9810
Time taken to sort array is861826nanoseconds

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

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

//Program
//(a) Dynamic Programming method

import java.util.Scanner;
public class knapsack1
{
public void solve(int wt[],int val[],int w,int n)
{
int i,j;
int [][]sol=new int[n+1][w+1];
for(i=0;i<=n;i++)
{
for(j=0;j<=w;j++)
{
if(i==0||j==0)
sol[i][j]=0;
else
if(wt[i]>j)
sol[i][j]=sol[i-1][j];
else
sol[i][j]=Math.max((sol[i-1][j]),(sol[i-1][j-wt[i]]+val[i]));
}
}
System.out.println("The optimal solution is "+sol[n][w]);
int selected[]=new int[n+1];
for(i=0;i<=n;i++)
selected[i]=0;
i=n;
j=w;
while(i>0&&j>0)
{
if(sol[i][j]!=sol[i-1][j])
{
selected[i]=1;
j=j-wt[i];
}
i--;
}
System.out.println("Items selected:");
for(i=0;i<n+1;i++)
if(selected[i]==1)
System.out.println(i+" ");
System.out.println();
}

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

public static void main(String args[])


{
Scanner scan= new Scanner(System.in);
knapsack1 ks= new knapsack1();
System.out.println("Enter number of elements");
int n=scan.nextInt();
int wt[]=new int[n+1];
int val[]=new int[n+1];
System.out.println("\nEnter weight for"+n+"elements");
for(int i=1;i<=n;i++)
wt[i]=scan.nextInt();
System.out.println("Enter the value for"+n+"elements");
for(int i=1;i<=n;i++)
val[i]=scan.nextInt();
System.out.println("\nEnter the knapsack weight");
int w=scan.nextInt();
ks.solve(wt,val,w,n);
}
}

output
Enter number of elements
3

Enter weight for3elements


10
20
30
Enter the value for3elements
1
2
3

Enter the knapsack weight


25
The optimal solution is 2
Items selected:
2

(b)Greedy method.

import java.util.Scanner;
public class knapsackgreedy
{
public static void main(String args[])
{
int i,j=0,max_qty,m,n;
float sum=0,max;

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

Scanner sc=new Scanner(System.in);


int array[][]=new int[20][20];
System.out.println("Enter the number of items");
n=sc.nextInt();
System.out.println("Enter the weight of each item");
for(i=0;i<n;i++)
array[0][i]=sc.nextInt();
System.out.println("Enter the value of each item");
for(i=0;i<n;i++)
array[1][i]=sc.nextInt();
System.out.println("Enter the maximum value of knapsack");
max_qty=sc.nextInt();
m=max_qty;
while(m>=0)
{
max=0;
for(i=0;i<n;i++)
{
if(((float)array[1][i])/(float)array[0][i]>max)
{
max=(((float)array[1][i])/(float)array[0][i]);
j=i;
}

}
if(array[0][j]>m)
{
System.out.println("Quantity of item number " +(j+1)+ "added is " +m);
sum+=m+max;
m=-1;
}
else
{
System.out.println("Quantity of item number " +(j+1)+ "added is "
+array[0][j]);
m-=array[0][j];
sum+=(float)array[1][j];
array[1][j]=0;
}
}
System.out.println("Total sum is "+sum);
}
}
output
Enter the number of items
3
Enter the weight of each item
18

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

15
10
Enter the value of each item
25
24
15
Enter the maximum value of knapsack
20
Quantity of item number 2added is 15
Quantity of item number 3added is 5
Total sum is 30.5

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

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.

Program
import java.util.Scanner;
public class dijkstra
{
int d[]=new int[10];
int p[]=new int[10];
int visited[]=new int[10];
public void dijk(int a[][], int s,int n)
{
int u=-1,v,i,j,min;
for(v=0;v<n;v++)
{
d[v]=99;
p[v]=-1;
}
d[s]=0;
for(i=0;i<n;i++)
{
min=99;
for(j=0;j<n;j++)
{
if(d[j]<min&&visited[j]==0)
{
min=d[j];
u=j;
}
}
visited[u]=1;
for(v=0;v<n;v++)
{
if((d[u]+a[u][v]<d[v])&&(u!=v)&&(visited[v]==0))
{
d[v]=d[u]+a[u][v];
p[v]=u;
}
}
}
}
void path(int v,int s)
{
if(p[v]!=-1)
path(p[v],s);
if(v!=s)
System.out.print("->"+v+"");

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

}
void display(int s,int n)
{
int i;
for(i=0;i<n;i++)
{
if(i!=s)
System.out.print(s+"");
path(i,s);
if(i!=s)
System.out.print("="+d[i]+"");
System.out.println();
}
}
public static void main(String args[])
{
int a[][]=new int[10][10];
int i,j,n,s;
System.out.println("Enter the number of vertices");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
System.out.println("Enter the weighted matrix");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=sc.nextInt();
System.out.println("Enter the source vertex");
s=sc.nextInt();
dijkstra tr=new dijkstra();
tr.dijk(a,s,n);
System.out.println("Shortest path between source"+s+"to remaining");
tr.display(s,n);
sc.close();
}
}
output
Enter the number of vertices
4
Enter the weighted matrix
0 10 40 99
10 0 99 20
40 99 0 30
99 20 30 0
Enter the source vertex
1
Shortest path between source1to remaining
1->0=10

1->0->2=50

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

1->3=20

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

Program

import java.util.Scanner;
public class kruskal
{
int parent[]=new int[10];
int find(int m)
{
int p=m;
while(parent[p]!=0)
p=parent[p];
return p;
}
void union(int i,int j)
{
if(i<j)
parent[i]=j;
else
parent[j]=i;
}
void krkl(int a[][],int n)
{
int v=0,u=0,min,k=0,i,j,sum=0;
while(k<n-1)
{
min=99;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(a[i][j]<min && i!=j)
{
min=a[i][j];
u=i;
v=j;
}
i=find(u);
j=find(v);
if(i!=j)
{
union(i,j);
System.out.println("("+u+","+v+")"+"="+a[u][v]);
sum=sum+a[u][v];
k++;

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

}
a[u][v]=a[v][u]=99;
}
System.out.println("The cost of minimum spanning tree="+sum);
}
public static void main(String args[])
{
int a[][]=new int [10][10];
int i,j;
System.out.println("Enter the number of vertices of graph");
Scanner sc=new Scanner(System.in);
int n;
n=sc.nextInt();
System.out.println("Enter the weighted vertex");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=sc.nextInt();
kruskal k=new kruskal();
k.krkl(a,n);
//sc.close();
}
}

output

Enter the number of vertices of graph


4
Enter the weighted vertex
0 10 40 99
10 0 99 20
40 99 00 30
99 20 30 0
(1,2)=10
(2,4)=20
(3,4)=30
The cost of minimum spanning tree=60

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

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

Program

import java.util.Scanner;
public class prims
{
public static void main(String args[])
{
int w[][]=new int [10][10];
int n,i,j,sr,k=0;
int min;
int sum=0;
int u=0,v=0;
int flag=0;
int sol[]=new int[10];
System.out.println("Enter the no of vertices");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
for(i=1;i<=n;i++)
sol[i]=0;
System.out.println("Enter the weighted graph");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
w[i][j]=sc.nextInt();
System.out.println("Enter the source vertex");
sr=sc.nextInt();
sol[sr]=1;
k=1;
while(k<=n-1)
{
min=99;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(sol[i]==1&&sol[j]==0)
if(i!=j&&min>w[i][j])
{
min=w[i][j];
u=i;
v=j;
}
sol[v]=1;
sum=sum+min;
k++;
System.out.println(u+"-->"+v+"="+min);
}

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

for(i=1;i<=n;i++)
if(sol[i]==0)
flag=1;
if(flag==1)
System.out.println("No spanning tree");
else
System.out.println("The cost of minimum spanning tree is"+sum);
sc.close();
}
}

output

Enter the no of vertices


6
Enter the weighted graph
0 60 10 99 99 99
60 0 99 20 40 70
10 99 0 99 99 50
99 80 99 0 99 80
99 40 99 99 0 30
99 70 50 80 30 0
Enter the source vertex
1
1-->3=10
3-->6=50
6-->5=30
5-->2=40
2-->4=20
The cost of minimum spanning tree is150

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

10.
Write Java programs to
(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.

import java.util.Scanner;
public class floyds{
void floyds(int w[][],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
w[i][j]=Math.min(w[i][j],w[i][k]+w[k][j]);
}
public static void main(String args[])
{
int a[][]=new int [10][10];
int n,i,j;
System.out.println("Enter the number of vertices");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
System.out.println("Enter the weighted matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=sc.nextInt();
floyds f=new floyds();
f.floyds(a,n);
System.out.println("The shortest path matrix is ");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
sc.close();
}
}
output
Enter the number of vertices
4
Enter the weighted matrix
0 10 40 99
10 0 99 20
40 99 0 30
99 20 30 0
The shortest path matrix is

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

0 10 40 30
10 0 50 20
40 50 0 30
30 20 30 0
(b) Implement Travelling Sales Person problem using Dynamic programming.

import java.util.Scanner;
class TSPExp
{
int weight[][],n,tour[],finalcost;
final int INF=1000;
TSPExp()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the number of nodes:=>");
n=s.nextInt();
weight= new int[n][n];
tour=new int[n-1];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i!=j){
System.out.println("Enter weight of "+(i+1)+" to "+(j+1)+" => ");
weight[i][j]=s.nextInt();
}
}
}
System.out.println();
System.out.println("Starting node assumed to be node1");
eval();
}
public int COST(int currentnode,int inputset[],int setsize)
{
if(setsize==0)
return weight[currentnode][0];
int min=INF;
int SetToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setsize;i++)
{
int k=0;
for(int j=0;j<setsize;j++)
{
if(inputset[i]!=inputset[j])
SetToBePassedOnToNextCallOfCOST[k++]=inputset[j];
}
int temp=COST(inputset[i],SetToBePassedOnToNextCallOfCOST,setsize-1);
if((weight[currentnode][inputset[i]]+temp)<min )
{
min=weight[currentnode][inputset[i]]+temp;

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

}
}
return min;
}
public int MIN(int currentnode,int inputset[],int setsize)
{
if(setsize==0)
return weight[currentnode][0];
int min=INF,minindex=0;
int SetToBePassedOnToNextCallCOST[]=new int[n-1];
for(int i=0;i<setsize;i++)
{
int k=0;
for(int j=0;j<setsize;j++)
{
if(inputset[i]!=inputset[j])
SetToBePassedOnToNextCallCOST[k++]=inputset[j];
}
int temp=COST(inputset[i],SetToBePassedOnToNextCallCOST,setsize-1);
if((weight[currentnode][inputset[i]]+temp)<min)
{
min=weight[currentnode][inputset[i]]+temp;
minindex=inputset[i];
}
}
return minindex;
}
public void eval()
{
int dummyset[]=new int[n-1];
for(int i=1;i<n;i++)
dummyset[i-1]=i;
finalcost=COST(0,dummyset,n-1);
constructtour();
}
public void constructtour()
{
int previousset[]=new int[n-1];
int nextset[]=new int[n-2];
for(int i=1;i<n;i++)
previousset[i-1]=i;
int setsize=n-1;
tour[0]=MIN(0,previousset,setsize);
for(int i=1;i<n-1;i++)
{
int k=0;
for(int j=0;j<setsize;j++)
{

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

if(tour[i-1]!=previousset[j])
nextset[k++]=previousset[j];
}
--setsize;
tour[i]=MIN(tour[i-1],nextset,setsize);
for(int j=0;j<setsize;j++)
previousset[j]=nextset[j];
}
display();
}
public void display()
{
System.out.println();
System.out.println("The tour is 1-");
for(int i=0;i<n-1;i++)
System.out.print(tour[i]+1+"-");
System.out.print("1");
System.out.println();
System.out.println("The final cost is"+finalcost);
}
}
class TSP
{
public static void main(String args[])
{
TSPExp obj=new TSPExp();
}
}
output
Enter the number of nodes:=>
3
Enter weight of 1 to 2 =>
10
Enter weight of 1 to 3 =>
20
Enter weight of 2 to 1 =>
30
Enter weight of 2 to 3 =>
40
Enter weight of 3 to 1 =>
50
Enter weight of 3 to 2 =>
60
Starting node assumed to be node1

The tour is 1-
2-3-1
The final cost is100

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

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.

Program

import java.util.Scanner;
import static java.lang.Math.pow;
public class subset{
void subset(int num,int n,int x[])
{
int i;
for(i=1;i<=n;i++)
x[i]=0;
for(i=n;num!=0;i--)
{
x[i]=num%2;
num=num/2;
}
}
public static void main(String args[])
{
int a[]=new int[10];
int x[]=new int[10];
int n,d,sum,present=0;
int j;
System.out.println("Enter the number of elements of set");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
System.out.println("Enter the elements of set");
for(int i=1;i<=n;i++)
a[i]=sc.nextInt();
System.out.println("Enter the positive integer sum");
d=sc.nextInt();
if(d>0){
for(int i=1;i<=Math.pow(2,n)-1;i++)
{
subset s=new subset();
s.subset(i,n,x);
sum=0;
for(j=1;j<=n;j++)
if(x[j]==1)
sum=sum+a[j];
if(d==sum)
{
System.out.print("Subset={");

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

present=1;
for(j=1;j<=n;j++)
if(x[j]==1)
System.out.print(a[j]+",");
System.out.print("}="+d);
System.out.println();
}
}
}
if(present==0)
System.out.println("Solution does not exist");
}
}

output

Enter the number of elements of set


5
Enter the elements of set
12345
Enter the positive integer sum
5
Subset={5,}=5
Subset={2,3,}=5
Subset={1,4,}=5

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

import java.util.*;
class Hamiltoniancycle
{
private int adj[][],x[],n;
public Hamiltoniancycle()
{
Scanner scr=new Scanner(System.in);
System.out.println("Enter number of nodes");
n=scr.nextInt();
x=new int[n];
x[0]=0;

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

for(int i=1;i<n;i++)
x[i]=-1;
adj=new int[n][n];
System.out.println("Enter the adjacency matrix");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
adj[i][j]=scr.nextInt();
}
public void nextValue(int k)
{
int i=0;
while(true)
{
x[k]=x[k]+1;
if(x[k]==n)
x[k]=-1;
if(x[k]==-1)
return;
if(adj[x[k-1]][x[k]]==1)
for(i=0;i<k;i++)
if(x[i]==x[k])break;
if(i==k)
if(k<n-1||k==n-1&&adj[x[n-1]][0]==1)
return;
}
}
public void getHcycle(int k)
{
while(true)
{
nextValue(k);
if(x[k]==-1)
return;
if(k==n-1)
{
System.out.println("\nSolution:");
for(int i=0;i<n;i++)
System.out.print((x[i]+1)+" ");
System.out.println("1");
}
else getHcycle(k+1);
}
}
}
class HamiltonianExp
{
public static void main(String args[])
{

CS&E 2016-2017 Batch


Govenment Enginerring College Hassan

Hamiltoniancycle obj=new Hamiltoniancycle();


obj.getHcycle(1);
}
}
output
Enter number of nodes
6
Enter the adjacency matrix
011100
101001
110110
101010
001101
010010

Solution:
1265341

Solution:
1265431

Solution:
1326541

Solution:
1345621

Solution:
1435621

Solution:
1456231

Term :
Ther is no problem. Any problem let me know

Creted by
4th sem Boys 2016-17
CS&E
Hassan-573201
All the best do well your exams Thank you

CS&E 2016-2017 Batch

You might also like