Professional Documents
Culture Documents
n2bgw Ig8ps
n2bgw Ig8ps
n2bgw Ig8ps
B Write a Java program to implement the Stack using arrays. Write Push(), Pop(),
and Display() methods to demonstrate its working.
2 A Design a superclass called Staff with details as StaffId, Name, Phone, Salary.
Extend this class by writing three subclasses namely Teaching (domain,
publications), Technical (skills), and Contract (period). Write a Java program to
read and display at least 3 staff objects of all three categories.
B Write a Java class called Customer to store their name and date_of_birth.
The date_of_birth format should be dd/mm/yyyy. Write methods to read customer
data as
<name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using
StringTokenizer class considering the delimiter character as “/”.
3 A Write a Java program to read two integers a andb. Compute a/b and print, when b is
not zero. Raise an exception when b is equal to zero.
B Write a Java program that implements a multi-thread application that has three
threads. First thread generates a random integer for every 1 second; second thread
computes the square of the number andprints; third thread will print the value of
cube of the number.
4 Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to
sort. Plot a graph of the time taken versus non graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using Java
how the divide- and-conquer method works along with its time complexity analysis:
worst case, average case and best case.
5 Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program for varied values of n> 5000, and record the time taken to
sort. Plot a graph of the time taken versus non graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using Java how
the divide- and-conquer method works along with its time complexity analysis: worst case,
average case and best case.
6 Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming method
(b) Greedy method.
7 From a given vertex in a weighted connected graph, find shortest paths to other vertices using
Dijkstra's algorithm. Write the program in Java.
8 Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal'salgorithm. Use Union-Find algorithms in your program.
9 Find Minimum Cost Spanning Tree of a given connected undirected graph using
Prim's algorithm.
1b.
Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods to
demonstrate its working.
import java.util.Scanner;
public class StackClass {
private int stack[];
private int tos=-1;
private int maxnumber;
public void push()
{
if(tos==maxnumber-1)
{
System.out.println("Stack Overflow");
return;
}
else
{
tos++;
System.out.println("Enter element to be pushed");
Scanner scan=new Scanner(System.in);
int element=scan.nextInt();
stack[tos]=element;
System.out.println("Element is pushed");
}
}
public void pop()
{
if(tos==-1)
{
System.out.println("Stack underflow");
return;
}
System.out.println("popped element is "+stack[tos]);
tos--;
}
public void display()
{
int count=tos;
if(count == -1)
System.out.println("Stack is empty");
for(int i=count;i>=0;i--)
{
System.out.println(stack[i]);
}
}
public static void main(String args[])
{
System.out.println("Enter stack size");
Scanner scan=new Scanner(System.in);
int size=scan.nextInt();
StackClass sc=new StackClass();
sc.maxnumber=size;
sc.stack=new int[size];
while(true)
{
System.out.println("Enter 1 to push 2 to pop 3 to display 4 to exit");
int option=scan.nextInt();
switch(option)
{
case 1:
sc.push();
break;
case 2:
sc.pop();
break;
case 3:
sc.display();
break;
case 4:
System.exit(0);
}
}
}
}
Output
2. a) Design a superclass called Staff with details as StaffId, Name, Phone, Salary. Extend this class by writing
three subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write a Java
program to read and display at least 3 staff objects of all three categories.
//staff class
import java.util.Scanner;
void display_staff_details()
{
System.out.print(Name+"\t"+StaffId+"\t"+Phone+"\t"+Salary+"\t");
//Teaching class
public class Teaching extends Staff{
String domain;
int no_publication;
void read_domain_publication()
{
System.out.println("Enter domain");
domain = scan.next();
System.out.println("Enter number of publications");
no_publication = scan.nextInt();
}
void display_domain_publication()
{
System.out.print(domain+"\t"+no_publication);
System.out.println("\n");
}
//Technical class
int period;
void read_contract_period()
{
System.out.println("Enter contract period");
period = scan.nextInt();
}
void display_contract_period()
{
System.out.print(period);
System.out.println("\n");
}
}
//Staffmain class
import java.util.Scanner;
System.out.println("Name\t"+"St_id\t"+"ph_no\t"+"salary\t"+"domain\t"+"no_publication\
n");
System.out.println("---------------------------------------------------------");
System.out.println("---------------------------------------------------------\n\n");
System.out.println("---------------------------------------------------------\n\n");
System.out.println("---------------------------------------------------------\n");
}
}
2b) Write a Java class called Customer to store their name and date_of_birth. The date_of_birth format
should be dd/mm/yyyy. Write methods to read customer data as
<name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using StringTokenizer class considering the
delimiter character as “/”.
import java.util.Scanner;
import java.util.StringTokenizer;
public class Customer {
String name,DOB;
Scanner scan = new Scanner( System.in );
void read_name_DOB()
{
void display_name_DOB()
{
StringTokenizer st = new StringTokenizer(DOB,"/");
//System.out.println("name of the customer-------->"+name);
String dd = st.nextToken();
String mm = st.nextToken();
String yy = st.nextToken();
System.out.println("<"+name+" ,"+dd+","+mm+","+yy+">");
}
3. a Write a Java program to read two integers a andb. Compute a/b and print, when b is not zero. Raise an exception
when b is equal to zero.
public class Exception2a {
public static void main(String[] args) {
Scanner scan = new Scanner( System.in );
int a = 0,b=0,result=0;
try {
int c = a / b;
result = c;
System.out.println("The result: "+result);
} catch(ArithmeticException ex) {
System.out.println("since b=0 thier is divide by zero exception");
}
}
}
OUTPUT1:
Enter 'a' value
4
Enter 'b' value
0
since b=0 thier is divide by zero exception
OUTPUT 2:
Enter 'a' value
4
Enter 'b' value
6
The result: 0
3.b Write a Java program that implements a multi-thread application that has three threads. First thread generates a
random integer for every 1 second; second thread computes the square of the number andprints; third thread will
print the value of cube of the number.
//class for square print
public class SquarePrint implements Runnable
{
public int x;
public SquarePrint(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread Square of " + x + " is: " + x * x);
}
}
//class for 3 threads
import java.util.*;
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
//main class
public class Threads_3b {
public static void main(String[] args)
{
A a = new A();
a.start();
}
OUTPUT:
Main Thread and Generated Number is 45
New Thread Square of 45 is: 2025
New Thread calculating and printing>>>>> Cube of 45 is: 91125
--------------------------------------
Main Thread and Generated Number is 25
New Thread Square of 25 is: 625
New Thread calculating and printing>>>>> Cube of 25 is: 15625
--------------------------------------
Main Thread and Generated Number is 71
New Thread Square of 71 is: 5041
New Thread calculating and printing>>>>> Cube of 71 is: 357911
--------------------------------------
Main Thread and Generated Number is 82
New Thread Square of 82 is: 6724
New Thread calculating and printing>>>>> Cube of 82 is: 551368
--------------------------------------
Main Thread and Generated Number is 68
New Thread Square of 68 is: 4624
New Thread calculating and printing>>>>> Cube of 68 is: 314432
--------------------------------------
4. Sort a given set of n integer elements using Quick Sort method and compute its time complexity. Run the
program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the time taken versus non
graph sheet. The elements can be read from a file or can be generated using the random number generator.
Demonstrate using Java how the divide- and-conquer method works along with its time complexity analysis: worst
case, average case and best case./*
import java.util.*;
/* Class QuickSort */
public class QuickSort
{
/* Quick Sort function */
public static int partition(int low,int high,int a[])
{
int i,j,key,temp;
i=low;
j=high+1;
key=a[low]; //assigning the first value in array as key.
while(i<=j)
{ do i++;
while(i<=high && key>=a[i]);
do j--;
while(j>=low && key<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;
}
public static void quick_sort(int low,int high,int a[])
{
int mid;
if(low<high)
{
mid=partition(low,high,a);
quick_sort(low,mid-1,a);//Call recursively to sort the left
part
quick_sort(mid+1,high,a); //Call recursively to sort the right
part
}
}
/* Main method */
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
Random ran = new Random();
System.out.println("Quick Sort Test\n");
int n, i;
/* Accept number of elements */
System.out.println("Enter number of integer elements");
n = scan.nextInt();
/* Create array of n elements */
int a[] = new int[n];
/* Accept elements */
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
a[i] = ran.nextInt(n);
for (i = 0; i < n; i++)
System.out.print(a[i]+" ");
long start = System.nanoTime ();
/* Call method sort */
quick_sort( 0, n-1,a);
long end= System.nanoTime();
/* Print sorted Array */
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(a[i]+" ");
System.out.println();
double total=end-start;
System.out.println (total/1000000000);
}
}
OUTPUT:
Quick Sort Test
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.utl.**
/* Class MergeSort */
b[k++] = a[i++] *
else
b[k++] = a[j++] *
while (i<=mii)
b[k++] = a[i++] *
while (j<=high)
b[k++] = a[j++] *
a[k] = b[k]*
if (low>=high)
return*
// recursively sort
simple_merge(a,low,mii,high)*
/* Main methoi */
int n, i*
n = scan.nextInt()*
/* Accept elements */
a[i] = ran.nextInt(n)*
System.out.print(a[i]+" ")*
sort(a, 0, n-1)*
System.out.print(a[i]+" ")*
System.out.println()*
iouble total=eni-start*
System.out.println (total/1000000000)*
}OUTPUT:
Merge Sort Test
6. Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming method (b) Greedy method.
import java.util.Scanner;
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
System.out.print("\t"+v[i][j]);
}
System.out.println("\n");
}
for(i=0;i<=n;i++)
x[i]=0;
i=n; //Number of Objects
j=m; //Capacity of Knapsack
while(i!=0 && j!=0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1; //objects selected
j=j-w[i]; //Remaining capacity
}
i--;
}
System.out.println("\nThe objects selected are :\n");
for(i=1;i<=n;i++)
{
if(x[i]==1)
System.out.print("\t"+i);
}
System.out.println("\n");
System.out.println("\nOptimal solution is "+profit);
OUTPUT:
3 20
2 15
The Resultant profit table:
0 0 0 0 0 0
0 0 12 12 12 12
0 10 12 22 22 22
0 10 12 22 30 32
0 10 15 25 30 37
1 2 4
Optimal solution is 37
import java.util.Scanner;
w[i]= scan.nextInt();
p[i]= scan.nextInt();
pp[i]= p[i]/w[i];
}
temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
System.out.println("PP ARRAY \n");
for (i =0; i<n; i++)
System.out.println("\t"+pp[i]+"\t"+w[i]+"\t"+p[i]);
System.out.println("\nprofit is "+profit);
}
}
OUTPUT:
Enter number of objects
4
Enter capacity of knapsack
5
profit is 38.33333333333333
7. From a given vertex in a weighted connected graph, find shortest paths to other vertices using
Dijkstra's algorithm. Write the program in Java.
import java.util.Scanner;
public class dijkstra
{
public static void dijkstra_soln(int n,int src,int cost[][])
{
int i,j,min;
int dis[]=new int[10];
int vis[]=new int[10];
for(i=1;i<=n;i++)
{
dis[i]=cost[src][i];
}
vis[src]=1; //starting vertex is included in S
for(i=1;i<=n-1;i++)
{
min=999;
int u=0;
for(j=1;j<=n;j++)
{
if(vis[j]==0 && (dis[j]<min))//Find the smallest element in the
Dist(u)
{
min=dis[j];
u=j;
}
vis[u]=1;
for(j=1;j<=n;j++)
{
if(vis[j]==0 &&((dis[u]+cost[u][j])<dis[j]))//Upadate the Dist[]
Matrix
{
dis[j]=(dis[u]+cost[u][j]);
}
}
}
for(i=1;i<=n;i++)
{
System.out.println(src+"-> "+i+"= "+dis[i]);
}
}
OUTPUT:
Enter number of vertices
5
Enter source vertex
1
Enter cost adjacent matrix
0 3 999 7 999
3 0 4 2 999
999 4 0 5 6
7 2 5 0 4
999 999 6 4 0
8. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal's algorithm. Use Union-Find algorithms in your program.
import java.utl.**
public class Kruskals
{
public int p[]=new int[10]*
public int cost[][]=new int[10][10]*
public int fni(int v)
{
while(p[v]!=0)
v=p[v]*
return v*
}
public voii union(int i,int j)
{
if(i<j)
p[j]=i*
else
p[i]=j*
}
voii Kruskal_Algo(int n)
{
int i,j,u,v,min,a=0,b=0,ne=1,mincost=0*
while(ne<n)
{
for(i=1,min=999*i<=n*i++)
{
for(j=1*j<=n*j++)
{
if(cost[i][j]<min)
{
a=i*b=j*
min=cost[i][j]*
}
}
}
if(min!=999)
{
u=fni(a)*v=fni(b)*
cost[a][b]=cost[b][a]=999*
if(u!=v)
{
System.out.println(ne++ +"eige("+a+","+b+")-->"+min)*
mincost+=min*
union(u,v)*
}
}
}
System.out.println("Cost of Spanning tree:"+mincost)*
}
public statc voii main(String[] args)
{
Kruskals K=new Kruskals()*
int i,j,n*
int cost[][]=new int[10][10]*
Scanner s=new Scanner(System.in)*
System.out.println("Enter the number of vertces:")*
n=s.nextInt()*
System.out.println("Enter the cost aijacency matrix:")*
for(i=1*i<=n*i++)
{
for(j=1*j<=n*j++)
K.cost[i][j]=s.nextInt()*
if(K.cost[i][j]==0)
K.cost[i][j]=999*
}
System.out.println("Kruskal's Soluton")*
K.Kruskal_Algo(n)*
}
}
OUTPUT:
Enter the number of vertces:
4
Enter the cost aijacency matrix:
0152
1 0 999 999
5 999 0 3
2 999 3 0
Kruskal's Soluton
1eige(1,2)-->1
2eige(1,4)-->2
3eige(3,4)-->3
Cost of Spanning tree:6
9. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Prim's algorithm
import java.util.Scanner;
OUTPUT:
Enter number of vertices
5
Enter cost adjacent matrix
0 11 9 7 8
11 0 15 14 13
9 15 0 12 14
7 14 12 0 6
8 13 14 6 0
prims soln
1 edge (1,4)7
2 edge (4,5)6
3 edge (1,3)9
4 edge (1,2)11
Minimum cost33
}
System.out.println("\nFloyds soln ");
floyds_soln(a,n);
System.out.println("Shortest path length matrix");
for (i = 0; i <n; i++)
{ for (j= 0; j<n; j++)
System.out.print(a[i][j]+" ");
System.out.println("\n");
}
}
OUTPUT:
Floyds soln
Shortest path length matrix
0 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0
import java.utl.Scanner*
int i, j,cost*
int n = in.nextInt()*
if(n==1)
System.exit(0)*
for(i=1*i<=n*i++)
for(j=1*j<=n*j++)
c[i][j] = in.nextInt()*
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*
for(i=1*i<=n*i++)
System.out.print(tour[i]+"->")*
System.out.println("1")*
if(start == n-1)
temp[j] = tour[j]*
temp[start+1] = tour[i]*
temp[i] = tour[start+1]*
if((c[tour[start]][tour[i]]+(ccost=tspip(c,temp,start+1,n)))<mincost)
mintour[k] = temp[k]*
}
}
tour[i] = mintour[i]*
return mincost*
OUTPUT:
**** TSP DYNAMIC PROGRAMMING *******
Enter the number of cities:
4
Enter the cost matrix
0 10 15 20
5 0 9 10
6 13 0 12
8 8 9 0
The entered cost matrix is
0 10 15 20
5 0 9 10
6 13 0 12
8 8 9 0
The accurate path is
1->2->4->3->1
The accurate mincost is 35
******* ************* ***************
11. Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n positive integers whose
SUM is equal to a given positive integer d. For example, if S ={1, 2, 5, 6, 8} and d= 9, there are two solutions
{1,2,6}and {1,8}. Display a suitable message, if the given problem instance doesn't have a solution.
import java.util.Scanner;
{
x[k] = 1;
if( s + w[k] == d)
{
System.out.println("subset = "+ ++count);
for( i=1 ; i <= k ; i++)
if ( x[i] == 1)
System.out.println(" " + w[i]);
System.out.println("\n");
}
}
}
OUTPUT 1:
1 2 5 6 8
Enter the sum
9
subset = 1
1
2
6
subset = 2
1
8
OUTPUT 2:
Enter number of elements
4
Enter the elements
2 4 6 8
Enter the sum
10
subset = 1
2
8
subset = 2
4
6
OUTPUT 3:
Enter number of elements
4
Enter the elements
1
2
3
3
Enter the sum
12
No subset possible
12. Design and implement in Java to find all Hamiltonian Cycles in a connected undirected Graph G of n
vertices using backtracking principle.
import java.util.Scanner;
if(k==n)
{
System.out.println("\n");
for(i=1;i<=n;i++)
System.out.print("\t"+x[i]); //printing Hamiltonian cycle
System.out.print("\t"+x[1]);
}
else
H_Cycle(G,n,k+1);
}
}
public static void main(String[] args)
{ hamiltonian ham=new hamiltonian();
int i,j,v1,v2,Edges,n;
int G[][]=new int[20][20];
Scanner scan = new Scanner( System.in );
System.out.println("\n\t Program for Hamiltonian Cycle ");
System.out.println("\n Enter the number of vertices of graph: ");
n = scan.nextInt();
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
G[i][j]=0;
ham.x[i]=0;
}
}
System.out.println("\n Enter the total number of edges: ");
Edges = scan.nextInt();
for(i=1;i<=Edges;i++)
{
System.out.println("\n Enter the edge: ");
v1 = scan.nextInt();
v2 = scan.nextInt();
G[v1][v2]=1;
G[v2][v1]=1;
}
ham.x[1]=1;
System.out.println("\n Hamiltonian cycle ...\n");
ham.H_Cycle(G,n,2);
}
OUTPUT:
1 2 6 5 4 3 1
1 3 2 6 5 4 1
1 3 4 5 6 2 1
1 4 3 5 6 2 1
1 4 5 6 2 3 1