CP7111 Advanced Data Structures Lab Record Implementation of Graph Search Algorithm Ex.No:1 Breadth First Search and Depth First Search Aim: To write a java program for the implementation of graph search algorithm using the concept Breadth First Search and Depth First Search. Algorithm: Step1: Start the program. Step2: Enter the number of vertices and edges. Step3: Give the edge information. Step4: Push the root node in the Stack or Queue. Step5: Loop until the Stack or queue is empty. Step6: Remove the node from the stack or Queue. Step7: Then find the path from source to destination. Step8: Stop the program. Source Code: import java.io.*; class Node { int data; Node link; } class QueueBFS { Node front,rear; QueueBFS() {
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
CP7111 Advanced Data Structures Lab Record
Implementation of Graph Search Algorithm
Ex.No:1 Breadth First Search and Depth First Search
Aim:
To write a java program for the implementation of graph search algorithm using the concept Breadth First Search and Depth First Search.
Algorithm:
Step1: Start the program.Step2: Enter the number of vertices and edges. Step3: Give the edge information.Step4: Push the root node in the Stack or Queue. Step5: Loop until the Stack or queue is empty. Step6: Remove the node from the stack or Queue. Step7: Then find the path from source to destination. Step8: Stop the program.
int temp; temp=front.data; front=front.link; return temp;
}else{
System.out.println("Empty queuebfs"); return -1;
} }} class Graph{
int g[][]; int v,e;int visited[]; int a,b;QueueBFS q=new QueueBFS();void createGraph()throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the number of vertices:"); v=Integer.parseInt(br.readLine());System.out.println("Enter the number of edges:"); e=Integer.parseInt(br.readLine());g=new int[v+1][v+1];
for(int i=1;i<=e;i++){
System.out.println("Enter the Edge information:"); System.out.println("From="); a=Integer.parseInt(br.readLine()); System.out.println("To="); b=Integer.parseInt(br.readLine()); g[a][b]=g[b][a]=1;
int g[][]; int v,e;int visited[];void createGraph1()throws IOException{
int a,b;BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("\n Enter Number Of Vertices = "); v=Integer.parseInt(br.readLine());System.out.print("\n Enter Number Of Edges = "); e=Integer.parseInt(br.readLine());g=new int[v+1][v+1]; for(int i=1;i<=e;i++){
System.out.print("\n Enter Edge Infomation "); System.out.print("\n From ="); a=Integer.parseInt(br.readLine()); System.out.print("\n To ="); b=Integer.parseInt(br.readLine()); g[a][b]=g[b][a]=1;
public static void main(String args[])throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int c;
boolean i=true; while(i) {
System.out.println("\n\n MAIN MENU"); System.out.println("\n 1.BFS \t 2.DFS \t 3.EXIT"); System.out.println("\n Enter ur Choice:"); c=Integer.parseInt(br.readLine()); switch(c) {
case 1: Graph g=new Graph(); g.createGraph(); g.callBfs();
break; case 2:
Graph1 g1 = new Graph1(); g1.createGraph1(); g1.callDFS();
break; case 3:
i=false;break;
}}
}}
P a g e 4 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
P a g e 5 | 54
CP7111 Advanced Data Structures Lab Record
RESULT:
Thus the java program for the implementation of graph search algorithm using the concept Breadth First and Depth First search has been executed successfully.
P a g e 6 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No:2 Prim’s Algorithm
Aim:
To write a java program for the implementation of graph search algorithm using the conceptPrim’s Algorithm.
Algorithm:
Step1: Start the programStep2: Enter the number of vertices and edges .Step3: Give the edge information.Step4: Enter the weight for each edge.Step5: Then calculate minimum cost.Step6: Find the Minimum Spanning Tree.Step7: Stop the program.
Source Code:
import java.io.*; import java.util.*;
class Graph{
int weight[][]=new int[20][20]; int visited[]=new int [20];int d[]=new int[20]; int p[]=new int[20]; int v,e;void creategraph()throws IOException{
int i,j,a,b,w;BufferedReader in=new BufferedReader( new InputStreamReader(System.in)); System.out.print("\nEnter number of vertices :"); v=Integer.parseInt(in.readLine());System.out.print("\nEnter number of Edges :"); e=Integer.parseInt(in.readLine());for ( i=1;i<=v;i++)
for( j=1;j<=v;j++)weight[i][j]=0;
for (i=1;i<=v;i++){
p[i]=visited[i]=0;d[i]=32767;
}
P a g e 7 | 54
CP7111 Advanced Data Structures Lab Record
for ( i=1;i<=e;i++){
System.out.print("\nEnter edge a,b and weight w :"); a=Integer.parseInt(in.readLine()); b=Integer.parseInt(in.readLine()); w=Integer.parseInt(in.readLine()); weight[a][b]=weight[b][a]=w;
public static void main(String args[])throws IOException{
Graph g=new Graph(); g.algo();
}}
P a g e 9 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of graph search algorithm using the concept prim’s algorithm has been executed successfully.
P a g e 10 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No:3 Kruskal’s Algorithm
Aim:
To write a java program for the implementation of graph search algorithm using the conceptKruskal’s Algorithm.
Algorithm:
Step1: Start the program.Step2: Enter the number of nodes in the undirected weighted graph. Step3: Give weight for each edge.Step4: Find the minimum spanning tree, which node forms a cycle it is removed. Step5: Then find the cost for spanning tree.Step6: Stop the program.
Source Code:
import java.io.*; import java.util.*; class Graphs{int i,n; int noe;int graph_edge[][]=new int[100][4]; int tree[][]=new int [10][10];int sets[][]=new int[100][10]; int top[]=new int[100];int cost=0;
int getNumber(){String str; int ne=0;InputStreamReader input=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(input);try{str=in.readLine();ne=Integer.parseInt(str);}catch(Exception e){System.out.println("I/O Error");}return ne;
P a g e 11 | 54
CP7111 Advanced Data Structures Lab Record
}
void read_graph(){System.out.print("Enter the no. of nodes in the undirected weighted graph ::"); n=getNumber();
noe=0;
System.out.println("Enter the weights for the following edges ::\n"); for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
System.out.print(" < "+i+" , "+j+" > ::"); int w;w=getNumber();if(w!=0){
int p1=find_node(graph_edge[i][1]); int p2=find_node(graph_edge[i][2]); if(p1!=p2){
System.out.print("The edge included in the tree is ::"); System.out.print("< "+graph_edge[i][1]+" , "); System.out.println(graph_edge[i][2]+" > ");; cost=cost+graph_edge[i][3]; tree[graph_edge[i][1]][graph_edge[i][2]]=graph_edge[i][3]; tree[graph_edge[i][2]][graph_edge[i][1]]=graph_edge[i][3]; for(int j=1;j<=top[p2];j++){
top[p1]++;sets[p1][top[p1]]=sets[p2][j];
}top[p2]=0;
}else{
System.out.println("Inclusion of the edge "); System.out.print(" < "+graph_edge[i][1]+" , ");System.out.println(graph_edge[i][2]+"> forms a cycle so it is removed\n\
n"); } }
System.out.println("Cost of the spanning tree : "+cost);}int find_node(int n){for(int i=1;i<=noe;i++){
Thus the java program for the implementation of graph search algorithm using the concept kruskal’s algorithm has been executed successfully.
P a g e 15 | 54
CP7111 Advanced Data Structures Lab Record
Implementation and application of Network flow and linear programming problems
Ex.No:4 Implementation of Maximum Flow and Minimum Cut
Aim:
To write a java program for the implementation of Network Flow by finding the maximum flow and minimum cut of a network.
Algorithm:
Step1: Start the program.Step2: Enter the number of nodes.Step3: Determine the Graph matrix.Step4: Enter the source and sink in the graph.Step5: Find the Maximum flow and minimum Cut set in the graph.Step6: Stop the program.
Source Code:
import java.util.ArrayList; import java.util.HashSet;import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner;import java.util.Set; public class NetworkFlowProb{
this.numberOfVertices = numberOfVertices; this.queue = new LinkedList<Integer>(); parent = new int[numberOfVertices + 1]; visited = new boolean[numberOfVertices + 1]; cutSet = new HashSet<Pair>();reachable = new ArrayList<Integer>(); unreachable = new ArrayList<Integer>();
P a g e 16 | 54
CP7111 Advanced Data Structures Lab Record
}public boolean bfs (int source, int goal, int graph[][]){
}public int networkFlow (int graph[][], int source, int destination){
int u, v;int maxFlow = 0; int pathFlow;int[][] residualGraph = new int[numberOfVertices + 1][numberOfVertices + 1]; for (int sourceVertex = 1; sourceVertex <= numberOfVertices; sourceVertex++){
for (int destinationVertex = 1; destinationVertex <= numberOfVertices; destinationVertex++)
System.out.println("Enter the source of the graph"); source= scanner.nextInt(); System.out.println("Enter the sink of the graph"); sink = scanner.nextInt();NetworkFlowProb networkFlowProb = new NetworkFlowProb(numberOfNodes); maxFlow = networkFlowProb.networkFlow(graph, source, sink); System.out.println("The Max flow in the graph is " + maxFlow); System.out.println("The Minimum Cut Set in the Graph is "); networkFlowProb.printCutSet();scanner.close();
}}class Pair{
public int source; public int destination;public Pair(int source, int destination){
Thus the java program for the implementation of Network Flow by finding the maximum flow and minimum cut of a network has been successfully executed.
P a g e 20 | 54
CP7111 Advanced Data Structures Lab Record
Implementation of Algorithm using Hill Climbing and Dynamic Programming Design Technique
Ex.No:5 Travelling Salesman Problem
Aim:
To write a java program for the Implementation of hill climbing using travelling salesman problem.
Algorithm:
Step1: Start the programStep2: Enter the number of nodes.Step3: Specify the weight for each edge.Step4: Assume the starting node.Step5: Find the tour and its cost.Step6: Stop the program.
Source Code:
import java.util.*; import java.text.*;class TSP{
int weight[][],n,tour[],finalCost; final int INF=1000;public TSP(){
}public int MIN(int currentNode,int inputSet[],int setSize){
if(setSize==0)return weight[currentNode][0]; int min=INF,minindex=0;int setToBePassedOnToNextCallOfCOST[]=new int[n-1]; for(int i=0;i<setSize;i++)//considers each node of inputSet{
System.out.println(); System.out.print("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 TSPExp{
public static void main(String args[]){
TSP obj=new TSP();}
}
P a g e 23 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of Hill climbing algorithm using travelling salesman problem has been executed successfully.
P a g e 24 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No:6 Longest Common Subsequences
Aim:
To write a java program for the Implementation of dynamic programming using longest common subsequences problem.
Algorithm:
Step1: Start the program.Step2: Enter the string1 and string2.Step3: Determine the common sequence by matching the strings.Step4: Find the length of longest common subsequence.Step5: Display the common sequence between the given input strings.Step6: Stop the program.
Source Code:
import java.util.*; class lcs{
static class cell{
int cost, parent;}static final int MAXLEN = 100;static cell m[][] = new cell[MAXLEN][MAXLEN]; static final int MATCH = 0;static final int INSERT = 1; static final int DELETE = 2; static int indel(char c){return 1;}static int match(char c, char d){
m[i][j]=new cell();String s = new String(); String t = new String();Scanner sc = new Scanner(System.in); System.out.println("Enter the String1:"); s=sc.next();System.out.println("Enter the String2:"); t=sc.next();s=" " + s; t=" " + t;int complen = string_compare(s,t);int lcslen = (s.length() + t.length() - 2 - complen) / 2; System.out.printf("length of longest common subsequence = %d\n", lcslen); System.out.printf("Common Sequence:",complen); reconstruct_path(s,t,s.length()-1,t.length()-1);
}}
P a g e 27 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of Dynamic Programming using longest common subsequences problem has been executed successfully.
P a g e 28 | 54
CP7111 Advanced Data Structures Lab Record
Implementation of Recursive Backtracking Algorithms
Ex.No:7 N Queens Problem
Aim:
To write a java program for implementation of Recursive Backtracking Algorithms using N Queens Problem.
Algorithm:
Step1: Start the program. Step2: Enter the board size.Step3: Then place the queen based on board size. Step4: Find the solution for given board size.Step5: Check the condition board size less than or equal to row and column the print ‘Q’. Step6: Otherwise print dot(.). Step7: Repeat Step5 until there is no solution possible. Step8: Stop the program.
Source Code:
import java.util.Scanner; public class Queens{
protected int boardSize; protected boolean[][] board; public Queens (int boardSize){
this.boardSize = boardSize;board = new boolean[boardSize][boardSize]; for (int row = 0; row < boardSize; row++)
board[row][column] = true;successful = placeQueen (column + 1); if (!successful){
board[row][column] = false; row++;
}}}return successful;
} } protected boolean threat (int row, int column)
{for (int c = 0; c < column; c++){
if (board[row][c]){
return true;} }
for (int c = 1; c <= column; c++){
if (row < c){
break;}
if (board[row - c][column - c]){
return true;} }
for (int c = 1; c <= column; c++){
if (row + c >= boardSize){
break;}
if (board[row + c][column - c]){
return true;
P a g e 30 | 54
CP7111 Advanced Data Structures Lab Record
} }return false;
}protected void outputBoard(){
System.out.println("Solution for board of size " + boardSize + ":"); for (int row = 0; row < boardSize; row++){
for (int column = 0; column < boardSize; column++){
if (board[row][column]){
System.out.print("Q ");}else{
System.out.print(". ");}}
System.out.println();}
System.out.println();}public void solve(){
if (placeQueen(0)){
outputBoard();}else{
System.out.println("There is no solution possible");} }
public static void main (String[] args){
Queens board;Scanner input = new Scanner (System.in);System.out.print("Enter the board Size: "); //Gain Size of board from user int boardSize = input.nextInt();input.close();board = new Queens(boardSize); board.solve();
}}
P a g e 31 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT:
RESULT:
Thus the java program for the implementation of recursive backtracking algorithm using NQueens problem has been executed successfully.
P a g e 32 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No:8 Permutations
Aim:
To write a java program for implementation of Recursive Backtracking Algorithms using Permutation Problem.
Algorithm:
Step1: Start the program. Step2: Enter the initial string.Step3: Find the permutation for given string.Step4: Check the condition for ending string which is less than or equal to value 1. Step5: Print the string.Step6: Stop the program.
Source Code:
import java.io.*; public class permutation{
public static void main(String args[]) throws IOException{
String str;System.out.println("Enter the initial string");BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); str=br.readLine();System.out.println("Permutations are :"); permute("", str);
Thus the java program for the implementation of recursive backtracking algorithm using Permutation problem has been executed successfully.
P a g e 34 | 54
CP7111 Advanced Data Structures Lab Record
Implementation of Randomized Algorithms
Ex.No:9 Quick Sort
Aim:
To write a java program for the implementation of Randomized Algorithms using Quick Sort problem.
Algorithm:
Step1: Start the program.Step2: Enter the limit for its elements.Step3: Check if low is less than or equal to high then, temp=a[low];
a[low]=a[high]; a[high]=temp;Step4: Then increment low and decrement high.Step5: Display the sorted array elements in ascending order. Step6: Stop the program.
Source Code:
import java.io.*; import java.util.Scanner;import java.util.Random; public class quicksort{
private static final Random rnd =new Random(); public static void main(String[] args){
int i;Scanner in=new Scanner(System.in); System.out.println(" Quick Sort\n");System.out.println("Enter the no. of elements in the array:\n"); int arr_val=in.nextInt();int array[]=new int[arr_val]; try{
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in)); System.out.println("\nEnter the Array Elements:\n");for(i=0;i<arr_val;i++){
array[i]=Integer.parseInt(br.readLine());}
}catch(Exception ex){}
P a g e 35 | 54
CP7111 Advanced Data Structures Lab Record
System.out.println("\nValues Before the sort:\n"); for(i = 0; i < array.length; i++)System.out.print( array[i]+" "); System.out.println("\n"); System.out.println("Pivot Values\n"); quickSort(array,0,array.length-1); System.out.print("\nValues after the sort:\n"); for(i = 0; i <array.length; i++){
}public static int partition(int arr[], int left, int right)
{ int i = left, j = right;int tmp;int pivot = arr[left + rnd.nextInt(right - left)]; System.out.println(+pivot);while (i <= j) { while (arr[i] < pivot)i++;
while (arr[j] > pivot)j--;
if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++;
j--;}
}; return i;
}
public static void quickSort(int arr[], int left, int right) { int index = partition(arr, left, right);
if (left < index - 1) quickSort(arr, left, index - 1); if (index < right)
quickSort(arr, index, right);}
}
OUTPUT:
P a g e 36 | 54
CP7111 Advanced Data Structures Lab Record
RESULT:
Thus the java program for the implementation of randomized algorithm using quick sort problem has been executed successfully.
P a g e 37 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No:10 Matrix Multiplication
Aim:
To write a java program for the implementation of Randomized Algorithms using Matrix Multiplication problem.
Algorithm:
Step1: Start the program.Step2: Enter the matrix dimension. Step3: Then create a matrices function.Step4: Fill the first matrix with the random numbers.Step5: Check the condition for the first matrix that number less than dimension. Step6: Then fill the second matrix with the random numbers.Step7: Check the condition for the second matrix that number less than dimension. Step8: Multiplying the matrices. Step9: Display the resulting matrix. Step10: Stop the program.
Scanner keyboard = new Scanner(System.in); System.out.printf("Type in the matrix dimension.\n"); int dimension = keyboard.nextInt();int matrix1[][] = new int[dimension][dimension]; int matrix2[][] = new int[dimension][dimension]; int result[][] = new int[dimension][dimension]; for (int i = 0; i < dimension; i++){
for (int j = 0; j < dimension; j++){ Random rand = new Random(); int r = rand.nextInt(9);matrix1 [i][j] = r;
}}
System.out.printf("\nMatrix One:\n");
P a g e 38 | 54
CP7111 Advanced Data Structures Lab Record
for (int i = 0; i < dimension; i ++){ System.out.printf("\n");for (int j = 0; j < dimension; j++)
Thus the java program for the implementation of randomized algorithm using matrix multiplication problem has been executed successfully.
P a g e 40 | 54
CP7111 Advanced Data Structures Lab Record
Implementation of various Locking and Synchronization Mechanisms for Concurrent Linked Lists, Concurrent Queues, and Concurrent Stacks.
Ex.No : 11 Concurrent Linked List
Aim:
To write a java program to implement the various locking and synchronization mechanisms for Concurrent Linked List.
Algorithm:
Step 1: Start the program.Step 2: Include the necessary packages. Step 3: Define the Linked Node definition.Step 4: Create a constructor to build a node with null and specified constructor. Step 5: Create a linked list class. Step 6: Check for assertion if the assertion is not true then it throws java.lang.assertion error. Step 7: Create a function to check if the list is empty or not.Step 8: Display the result. Step 9: Stop the program.
} catch (Exception x) { print("threw an Exception!!!\n" + x);
}}
};
Runnable runB = new Runnable() { public void run() {enf.addItem("Hello!");
}};
try {Thread threadA1 = new Thread(runA, "A");
P a g e 42 | 54
CP7111 Advanced Data Structures Lab Record
threadA1.start();
Thread.sleep(500);
Thread threadA2 = new Thread(runA, "B"); threadA2.start();
Thread.sleep(500);
Thread threadB = new Thread(runB, "C"); threadB.start();
Thread.sleep(1000);
threadA1.interrupt();threadA2.interrupt();
} catch (InterruptedException x) {}
}}
P a g e 43 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT :
RESULT :
Thus a java program to implement the various locking and synchronization mechanisms for Concurrent Linked List has been executed successfully.
P a g e 44 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No : 12 Concurrent Queue
Aim:
To write a java program to implement producer consumer problem using concurrent blocking Queue.
Algorithm:
Step 1: Start the program.Step 2: Include the necessary packages.Step 3: Create the shared object for the class using blocking queue.Step 4: Create producer class in java.Step 5: Create consumer class in java.Step 6: Display the result.Step 7: Stop the program.
Source Code:
import java.io.*; import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level;import java.util.logging.Logger; public class ProducerConsumerPattern{
public static void main(String args[]){
BlockingQueue sharedQueue = new LinkedBlockingQueue(); Thread prodThread = new Thread(new Producer(sharedQueue)); Thread consThread = new Thread(new Consumer(sharedQueue)); prodThread.start();consThread.start();
}}
class Producer implements Runnable{
private final BlockingQueue sharedQueue; public Producer(BlockingQueue sharedQueue){this.sharedQueue = sharedQueue;}public void run(){for(int i=0; i<10; i++)
Thus a java program to implement producer consumer problem using concurrent blocking Queue has been successfully executed.
P a g e 47 | 54
CP7111 Advanced Data Structures Lab Record
Ex.No : 13 Concurrent Stack
Aim:
To write a java program to implement concurrent stack using push and pop.
Algorithm:
Step 1: Start the program.Step 2: Include the necessary packages.Step 3: Create a class stackimpl2Step 4: Initialize the stack using push and pop.Step 5: Create a wait() method that is called to pop the waiting element.Step 6: Create a notify() method to notify the popped elements.Step 7: Stackuser class has been created to extends thread.Step 8: Start Daemon thread using set daemon.Step 9: Start this thread.Step10: Display the result.
Source Code:
Import java.io.*; class StackImpl2{
private Object[] stackArray; private volatile int topOfStack; StackImpl2 (int capacity){
stackArray = new Object[capacity]; topOfStack = -1;
}public synchronized Object pop(){
System.out.println(Thread.currentThread() + ": popping"); while (isEmpty())try{
System.out.println(Thread.currentThread() + ": waiting to pop"); wait(); // (1)
public static void main(String[] args)throws InterruptedException{ // (11)
StackImpl2 stack = new StackImpl2(5); new StackPusher("A", stack);new StackPusher("B", stack); new StackPopper("C", stack);System.out.println("Main Thread sleeping."); Thread.sleep(10);System.out.println("Exit from Main Thread.");
}}
P a g e 50 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT :
RESULT :
Thus to write a java program to implement concurrent stack using push and pop has been executed successfully.
P a g e 51 | 54
CP7111 Advanced Data Structures Lab Record
Developing applications involving concurrency.
Ex.No : 14 Sleeping Barber Problem
Aim:To write a java program to implement Sleeping Barber problem using Concurrency.
Algorithm:
Step 1: Import the header files.Step 2: Declare the number of chairs and barbers in the shop Step 3: Enter the number of customer.Step 4: If there is no customer to be served, the barber goes to sleep.Step 5:If a customer enters the barber shop whole chairs are occupied, then the customer
leaves the Shop. Step 6: If the barber is busy, but chairs are available in waiting room then the customer
sits in one of the free chairs until the barber is idle.Step 7: Barber class which extends threads is used to simulate multiple sleeping barbers
static int cnum=1,n,ch,n1;public static void main(String[] args){ try
{BufferedReaderbr=newBufferedReader(new InputStreamReader(System.in)); em1 e=new em1();cust c=new cust(); int j;System.out.println("Enter no of Chairs including two barber Chairs: "); ch=Integer.parseInt(br.readLine()); System.out.println("Enter no of Customers : "); n=Integer.parseInt(br.readLine());
e.start();if(ch<n){
n1=n-ch;System.out.println(n1+" Customers Leaved from the Shop"); n=n-n1;while(cnum<=n){
int t=c.disp(cnum++);System.out.println("Barber1 serves " +" Customer " + t); Thread.sleep(1000);
}}else{
while(cnum<=n){
int t=c.disp(cnum++);System.out.println("Barber1 serves " +" Customer " + t); Thread.sleep(1000);
}}System.out.println("Barber1 sleeps ");
}catch(Exception e){}
}}
P a g e 53 | 54
CP7111 Advanced Data Structures Lab Record
OUTPUT :
RESULT :
Thus a java program to implement Sleeping Barber problem using Concurrency has been executed successfully.