Академический Документы
Профессиональный Документы
Культура Документы
ME/CSE
CP7111
ADVANCED DATA STRUCTURES LABORATORY
LAB MANUAL
BY
V.GOPALA KRISHNAN,
Assistant Professor
V.GOPALAKRISHNAN AP/CSE
MBCET
ME/CSE
Ex.No :1
Date :
AIM:
To write a java program to perform a Breadth First Search in the given graph.
ALGORITHM:
V.GOPALAKRISHNAN AP/CSE
MBCET
ME/CSE
PROGRAM:
import java.io.*;
class bfs
{
public static void main(String args[])throws IOException
{
int i,n,j,k;
System.out.println("No of vertices:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
int q[]=new int[10];
int m[]=new int[10];
int a[][]=new int[10][10];
for(i=0;i<n;i++)
{
m[i]=0;
}
System.out.println("\n Enter 1 if edge is present,0 if not");
for(i=0;i<n;i++)
{
System.out.println("\n");
for(j=i;j<n;j++)
{
System.out.println("Edge between"+(i+1)+"and"+(j+1)+":");
a[i][j]=Integer.parseInt(br.readLine());
a[j][i]=a[i][j];
}
a[i][i]=0;
}
System.out.println("\n Order of accessed nodes:\n");
q[0]=0;
m[0]=1;
int u;
int node=1;
V.GOPALAKRISHNAN AP/CSE
MBCET
ME/CSE
int beg1=1;
int beg=0;
while(node>0)
{
u=q[beg];
beg++;
System.out.println(""+(u+1));
node--;
for(j=0;j<n;j++)
{
if(a[u][j]==1)
{
if(m[j]==0)
{
m[j]=1;
q[beg1]=j;
node++;
beg1++;
}
}
}
}
}
}
OUTPUT :
F:\ds>javac bfs.java
F:\ds>java bfs
Number of vertices: 6
Enter 1 if edge is present, 0 if not
Edges between 1 and 1: 0
1 and 2: 1
1 and 3: 1
1 and 4: 1
V.GOPALAKRISHNAN AP/CSE
MBCET
ME/CSE
1 and 5: 0
1 and 6: 0
Edges between 2 and 2: 0
2 and 3: 1
2 and 4: 0
2 and 5: 1
2 and 6: 0
Edges between 3 and 3: 0
3 and 4: 1
3 and 5: 1
3 and 6: 1
Edges between 4 and 4: 0
4 and 5: 0
4 and 6: 1
Edges between 5 and 3: 0
5 and 4: 0
Edges between 6 and 6: 0
V.GOPALAKRISHNAN AP/CSE
MBCET
ME/CSE
RESULT:
Thus the java program for performing breadth first search algorithm has been executed
successfully and the output is verified.
V.GOPALAKRISHNAN AP/CSE
MBCET
ME/CSE
Ex.No :2
Date
AIM:
To write a java program to perform a Depth First Search in the given graph.
ALGORITHM:
1.Get the number of vertices.
2.To construct edges of graph get 1if edge is present else 0 and repeat the same for all the
vertices of the graph.
3.Store edges in adjacency matrix a[][] and traverse from source node.
4.Initially store m[] with zero .since nodes in graph are not visited. if visited make m[] as
one.
5.To access the order of nodes, for each node check the node is visited or not using m[].
6. In dfs() method ,node visited is marked as one,m[]=1.next node j is traversed by
checking the condition that edge between i and j is present using adjacency matrix a[][]=1 and next
node to be traversed is not visited, m[]=0.
7.The above step is repeated for all the nodes in the graph.
8.The order of accessed node is ouputed.
V.GOPALAKRISHNAN AP/CSE
MBCET
ME/CSE
PROGRAM:
import java.io.*;
class dfs
{
static void dfs(int a[][], int m[], int i, int n)
{
int j;
System.out.println("\t" + (i+1));
m[i] = 1;
for(j=0; j<n; j++)
if(a[i][j]==1 && m[j]==0)
dfs(a,m,j,n);
}
MBCET
ME/CSE
a[j][i]=a[i][j];
}
a[i][i] = 0;
}
System.out.println("\nOrder of accessed nodes : \n");
for (i=0; i<n; i++)
if (m[i]==0)
dfs(a,m,i,n);
}
}
OUTPUT :
F:\ds>javac dfs.java
F:\ds>java dfs
Number of vertices: 6
Enter 1 if edge is present, 0 if not
Edges between 1 and 1: 0
1 and 2: 1
1 and 3: 1
1 and 4: 1
1 and 5: 0
1 and 6: 0
Edges between 2 and 2: 0
2 and 3: 1
2 and 4: 0
2 and 5: 1
2 and 6: 0
Edges between 3 and 3: 0
3 and 4: 1
3 and 5: 1
3 and 6: 1
Edges between 4 and 4: 0
4 and 5: 0
4 and 6: 1
Edges between 5 and 3: 0
V.GOPALAKRISHNAN AP/CSE
MBCET
ME/CSE
5 and 4: 0
Edges between 6 and 6: 0
V.GOPALAKRISHNAN AP/CSE
10
MBCET
ME/CSE
RESULT:
Thus the java program for performing depth first search algorithm has been executed successfully
and the output is verified.
V.GOPALAKRISHNAN AP/CSE
11
MBCET
ME/CSE
Ex.No :3
NETWORKFLOW PROBLEM
Date :
AIM:
To write a java program to find Maxflow and Mincut in the given network.
ALGORITHM:
V.GOPALAKRISHNAN AP/CSE
12
MBCET
ME/CSE
PROGRAM:
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;
13
MBCET
ME/CSE
while (!queue.isEmpty())
{
element = queue.remove();
destination = 1;
while (destination <= numberOfVertices)
{
if (graph[element][destination] > 0 && !visited[destination])
{
parent[destination] = element;
queue.add(destination);
visited[destination] = true;
}
destination++;
}
}
if (visited[goal])
{
pathFound = true;
}
return pathFound;
}
14
MBCET
ME/CSE
int u, v;
int maxFlow = 0;
int pathFlow;
int[][] residualGraph = new int[numberOfVertices + 1][numberOfVertices + 1];
/*max flow*/
while (bfs(source, destination, residualGraph))
{
pathFlow = Integer.MAX_VALUE;
for (v = destination; v != source; v = parent[v])
{
u = parent[v];
pathFlow = Math.min(pathFlow, residualGraph[u][v]);
}
for (v = destination; v != source; v = parent[v])
{
u = parent[v];
residualGraph[u][v] -= pathFlow;
residualGraph[v][u] += pathFlow;
}
maxFlow += pathFlow;
}
15
MBCET
ME/CSE
V.GOPALAKRISHNAN AP/CSE
16
MBCET
ME/CSE
17
MBCET
ME/CSE
scanner.close();
}
}
class Pair
{
public int source;
public int destination;
public Pair()
{
}
}
OUTPUT :
F:\ds>javac NetworkFlowProb.java
F:\ds>java NetworkFlowProb
Enter the number of nodes
6
Enter the graph matrix
0 16 13 0 0 0
0 0 10 12 0 0
0 4 0 0 14 0
0 0 9 0 0 20
000704
000000
Enter the source of the graph
1
Enter the sink of the graph
V.GOPALAKRISHNAN AP/CSE
18
MBCET
ME/CSE
6
The Max flow in the graph is 23
The Minimum Cut Set in the Graph is
2-4
5-6
5-4
V.GOPALAKRISHNAN AP/CSE
19
MBCET
ME/CSE
RESULT:
Thus the java program to find maxflow and mincut in the given network has been executed
successfully and the output is verified.
V.GOPALAKRISHNAN AP/CSE
20
MBCET
ME/CSE
DIJIKSTRAS ALGORITHM
Ex.No :4
Date :
AIM:
To write a java program to find the shortest path from source to all nodes using dijikstra's
algorithm in the given graph.
ALGORITHM:
1. Declare all necessary variables and initialize those variables.
2. Get the number of vertices and adjacency matrix.
3. Get the source node and store it in source variable.
4. Create a object for the class DijikstraQueue to access the method dijikstra-algorithm.
5. In this method get the copy of the adjacency matrix. Add the source into the queue.
6. Access getNodewithMinimumDistanceFromQueue,in this get the minimum capacity
vertice and add it to the settle set.
7. Keeping the distance of the node,handle the neighbours of the source and add them to
the queue.After handling the source,remove it from queue.
8. Again handle the nodes that are in queue as the same steps that before we performed.
9. While queue is empty stop the process and then we get the shortest path.
10. Finally, the shortest path from source to each other node is retutn.
V.GOPALAKRISHNAN AP/CSE
21
MBCET
ME/CSE
PROGRAM:
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
public class DijkstraQueue
{
private int distances[];
private Queue<Integer> queue;
private Set<Integer> settled;
private int number_of_nodes;
private int adjacencyMatrix[][];
22
MBCET
ME/CSE
distances[i] = Integer.MAX_VALUE;
}
queue.add(source);
distances[source] = 0;
while (!queue.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromQueue();
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
23
MBCET
ME/CSE
return node;
}
24
MBCET
ME/CSE
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
25
MBCET
ME/CSE
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
OUTPUT :
F:\ds>javac DijikstraQueue.java
F:\ds>java DijikstraQueue
Enter the number of vertices
5
Enter the Weighted Matrix for the graph
07002
00102
00040
00500
03850
Enter the source
1
The Shorted Path to all nodes are
1 to 1 is 0
1 to 2 is 5
1 to 3 is 6
1 to 4 is 7
1 to 5 is 2
V.GOPALAKRISHNAN AP/CSE
26
MBCET
ME/CSE
RESULT:
Thus the java program to find shortest path from source to all nodes using dijikstras
algorithm in the given graph has been executed successfully and the output is verified.
V.GOPALAKRISHNAN AP/CSE
27
MBCET
ME/CSE
Ex.No :5
Date :
AIM:
To write a java program to find the shortest path and minimum cost for travelling
salesperson problem.
ALGORITHM:
1. Declare all necessary variables and initialize those variables.
2. Create a object for the class TSP.
3. Get the number of nodes and weight of each edges.
4. The eval() method declares and initializes the dummyset array.
5. The cost() method finds the final cost by finding the cost of each path.
6. The constructor()method finds the path in terms of tour from the source node and
again it reaches the source.
7. From among all the tour paths the one with minimum cost is selected as the best
path.
8. Using display() method the tour path is return along with final cost as the result of
the travelling sales person problem.
V.GOPALAKRISHNAN AP/CSE
28
MBCET
ME/CSE
PROGRAM:
import java.util.*;
import java.text.*;
class TSP
{
int weight[][],n,tour[],finalCost;
final int INF=1000;
public TSP()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no. 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.print("Enter weight of "+(i+1)+" to "+(j+1)+":=>");
weight[i][j]=s.nextInt();
}
}
}
System.out.println();
System.out.println("Starting node assumed to be node 1.");
eval();
}
public int COST(int currentNode,int inputSet[],int setSize)
{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
V.GOPALAKRISHNAN AP/CSE
29
MBCET
ME/CSE
30
MBCET
ME/CSE
{
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++)
{
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];
V.GOPALAKRISHNAN AP/CSE
31
MBCET
ME/CSE
}
display();
}
public void display()
{
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();
}
}
OUTPUT :
F:\ds>javac TSPExp.java
F:\ds>java TSPExp
Enter number of nodes: 4
Enter weight of 1 to 2:5
Enter weight of 1 to 3:3
Enter weight of 1 to 4:14
Enter weight of 2 to 1:6
Enter weight of 2 to 3:5
Enter weight of 2 to 4:60
Enter weight of 3 to 1:2
Enter weight of 3 to 2:1
Enter weight of 3 to 4:7
V.GOPALAKRISHNAN AP/CSE
32
MBCET
ME/CSE
V.GOPALAKRISHNAN AP/CSE
33
MBCET
ME/CSE
RESULT:
Thus the java program to find the shortest path and minimum cost for travelling
salesperson problem has been executed successfully and the output is verified.
V.GOPALAKRISHNAN AP/CSE
34
MBCET
ME/CSE
N -QUEENS PROBLEM
Ex.No :6
Date :
AIM:
To write a java program to place the N number of Queens in a N*N chess board.
ALGORITHM:
1. Declare all necessary variables and initialize those variables.
2. Get the number of Queens and store it in the variable N.
3. Call enumerate() method and create array a and initialize it.
4. By using the method overloading concept,place the queens one by one.
5. Then by using isconsistent method to check that no two queens should be placed in the
diagonal or in same row or column.
6. Place the queens in the board by satisfying the conditions and mark the remaining place
as *.
7. Finally the output will display all the possible ways to place the queens in chess board.
V.GOPALAKRISHNAN AP/CSE
35
MBCET
ME/CSE
PROGRAM:
import java.util.*;
public class Queens
{
public static boolean isConsistent(int[] q, int n)
{
for (int i = 0; i < n; i++)
{
if (q[i] == q[n])
System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
public static void enumerate(int N)
{
int[] a = new int[N];
enumerate(a, 0);
}
public static void enumerate(int[] q, int n)
V.GOPALAKRISHNAN AP/CSE
36
MBCET
ME/CSE
{
int N = q.length;
if (n == N) printQueens(q);
else
{
for (int i = 0; i < N; i++)
{
q[n] = i;
if (isConsistent(q, n)) enumerate(q, n+1);
}
}
}
public static void main(String args[])
{
Scanner S=new Scanner(System.in);
System.out.print("Enter no. of Queens: ");
int N = S.nextInt();
enumerate(N);
}
}
OUTPUT :
F:\ds>javac Queens.java
F:\ds>java Queens
Enter number of Queens: 4
*Q**
***Q
Q***
**Q*
**Q*
Q***
***Q
*Q**
V.GOPALAKRISHNAN AP/CSE
37
MBCET
ME/CSE
RESULT:
Thus the java program to place the N number of queens in a N*N chess board has been
executed successfully and the output is verified.
V.GOPALAKRISHNAN AP/CSE
38
MBCET
ME/CSE
Ex.No :7
GRAPH COLORING
Date :
AIM:
To write a java program to implement graph coloring using recursive backtracking with the
given number of colors.
ALGORITHM:
1. Get the number of vertices and store it in the variable n.
2. Create adjacency matrix,using for loop defines edges between the nodes are present or not.
3. Get the number of colors available and store it in the variable m.
4. mcolouring() method calls another method nextvalue().
5. This method checks the next node value, here nodes are arranged as per the number of
colors available.
6. No two nodes have the same color nearly.
7. For n number of nodes the solution of the graph coloring is displayed.
8. If no solutions are present for the given input then it displays no possible solutions.
V.GOPALAKRISHNAN AP/CSE
39
MBCET
ME/CSE
PROGRAM:
import java.io.*;
public class GraphColoring
{
static int [][] G;
static int [] x;
static int n, m;
static boolean found = false;
G = new int[n+1][n+1];
x = new int[n+1];
40
MBCET
ME/CSE
41
MBCET
ME/CSE
return;
for(j=1; j<=n; j++)
if( (G[k][j] != 0) && (x[k] == x[j]) )
break;
if(j == n+1)
return;
}
}
}
OUTPUT :
F:\ds>javac GraphColoring.java
F:\ds>java GraphColoring
Enter the number of vertices : 5
If edge between the following vertices enter 1 else 0
1 and 2: 1
1 and 3: 1
1 and 4: 0
1 and 5: 0
2 and 3: 1
2 and 4: 0
2 and 5: 1
3 and 4: 1
3 and 5: 0
4 and 5:1
Enter the number of colors available:3
Solution:
1 2 3 1 3
1 3 2 1 2
2 1 3 1 2
3 1 2 1 2
3 2 1 2 1
V.GOPALAKRISHNAN AP/CSE
42
MBCET
ME/CSE
RESULT:
Thus the java program to color the nodes in the graph using recursive backtracking with the
number of colors has been executed successfully and the output is verified.
V.GOPALAKRISHNAN AP/CSE
43
MBCET
ME/CSE
Ex.No :8
QUICKSORT
Date :
AIM:
To write a java program to perform Quicksort using randomized algorithm.
ALGORITHM:
1. Create an object for the class QuickSort.
2. generateRandomNumber() method generates seven input values randomly to be sorted.
3. quicksort() method sorts the input list by finding the 'pivot' element in the list input.
4. This list can be split into two parts and sorted in the arraylist 'less' and 'greater'.
5. concatenate() method gets the 'less','pivot','greater' as inputs and concatenates them and
provide a new sorted list.
6. This new list is the result which is quick sorted.
V.GOPALAKRISHNAN AP/CSE
44
MBCET
ME/CSE
PROGRAM:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.lang.*;
public class QuickSort
{
public static void main(String[] args)
{
QuickSort app = new QuickSort();
List<Integer> input = app.generateRandomNumbers(7);
System.out.println(input);
System.out.println(app.quicksort(input));
}
private List<Integer> quicksort(List<Integer> input)
{
if(input.size() <= 1)
{
return input;
}
int middle = (int) Math.ceil((double)input.size() / 2);
int pivot = input.get(middle);
List<Integer> less = new ArrayList<Integer>();
List<Integer> greater = new ArrayList<Integer>();
for (int i = 0; i < input.size(); i++)
{
if(input.get(i) <= pivot)
{
if(i == middle)
{
continue;
}
less.add(input.get(i));
}
V.GOPALAKRISHNAN AP/CSE
45
MBCET
ME/CSE
Else
{
greater.add(input.get(i));
}
}
list.add(pivot);
return list;
}
private List<Integer> generateRandomNumbers(int n)
{
List<Integer> list = new ArrayList<Integer>(n);
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(n * 10));
V.GOPALAKRISHNAN AP/CSE
46
MBCET
ME/CSE
return list;
}
}
OUTPUT :
F:\ds>javac QuickSort.java
F:\ds>java QuickSort
[58,59,30,25,10,51,53]
[10,25,30,51,53,58,59]
V.GOPALAKRISHNAN AP/CSE
47
MBCET
ME/CSE
RESULT:
Thus the java program to perform Quicksort using randomized algorithm has been
executed successfully and the output is verified.
V.GOPALAKRISHNAN AP/CSE
48
MBCET
ME/CSE
Ex.No :9
BANKERS ALGORITHM
Date :
AIM:
To write a java program to allocate the resources for processes using bankers algorithm.
ALGORITHM:
1. Get the number of processes and store it in the variable pr.
2. Get the number of resources and store it in the variable res.
3. Each resource each process is currently holding is represented by the allocation matrix and
store it in all[][] which is the two dimensional array.
4. Get the max matrix ,it defines the maximum demand of each process and store it in
max[][] which is the two dimensional array.
5. calculate the need matrix which indicates the remaining resource need of each process it
can be obtained by subtracting the allocation matrix from the max matrix.
6. Each resource the system currently has available is denoted by the availability matrix and
store it in avail[] which is the one dimensional array.
7. For each process the flag is set to -1 then print busy.
8. Allocate the resources for each processes without any deadlock.
9. Flag[] array can be used to store the flag values.
10. Ord[] array can be used to store the order of process.
V.GOPALAKRISHNAN AP/CSE
49
MBCET
ME/CSE
PROGRAM:
import java.io.*;
class Bankers
{
public static void main(String args[])throws IOException
{
int all[][]=new int[10][10];
int max[][]=new int[10][10];
int need[][]=new int[10][10];
int avail[]=new int[10];
int ord[]=new int[10];
int flags[]=new int[10];
int i,j,pr,res,count=0,flag=0;
DataInputStream dis=new DataInputStream(System.in);
System.out.println(Enter no of processes : );
pr=Integer.parseInt(dis.readLine());
System.out.println(Enter no. of resources : );
res=Integer.parseInt(dis.readLine());
System.out.println(Enter allocation matrix : );
for(i=0;i<pr;i++)
{
for(j=0;j<res;j++)
{
all[i][j]=Integer.parseInt(dis.readLine());
}
}
System.out.println(Enter max matrix : );
for(i=0;i<pr;i++)
{
for(j=0;j<res;j++)
{
max[i][j]=Integer.parseInt(dis.readLine());
need[i][j]=max[i][j]-all[i][j];
V.GOPALAKRISHNAN AP/CSE
50
MBCET
ME/CSE
}
}
System.out.println(Enter avail matrix : );
for(j=0;j<res;j++)
{
avail[j]=Integer.parseInt(dis.readLine());
}
for(j=0;j<pr;j++)
{
flags[j]=-1;
System.out.println(Busy);
}
System.out.println(Need matrix : );
for(i=0;i<pr;i++)
{
for(j=0;j<res;j++)
{
System.out.print(need[i][j]+ );
}
System.out.println();
}
int t=0;
while(count<pr)
{
for(i=0;i<pr;i++)
{
if(flags[i]==-1)
{
System.out.print(i =+i+ );
flag=0;
for(j=0;j<res;j++)
{
if(need[i][j]>avail[j])
{
V.GOPALAKRISHNAN AP/CSE
51
MBCET
ME/CSE
}
}
System.out.print(flag =+flag+ );
if(flag==0)
{
for(j=0;j<res;j++)
{
avail[j]=avail[j]+all[i][j];
}
count++;
ord[t++]=i;
flags[i]=1;
}
System.out.print(c =+count+ );
for(j=0;j<res;j++)
System.out.print(avail[j]);
System.out.println();
}
}
}
System.out.println(Order);
for(i=0;i<pr;i++)
{
System.out.print(ord[i]+ );
}
}
}
OUTPUT :
F:\ds>javac Bankers.java
F:\ds>java Bankers
Enter no of processes :
5
Enter no. of resources :
V.GOPALAKRISHNAN AP/CSE
52
MBCET
ME/CSE
4
Enter allocation matrix :
0
0
1
2
1
0
0
0
1
3
5
4
0
6
3
2
0
0
1
4
Enter max matrix :
0
0
1
2
1
7
5
0
2
3
5
V.GOPALAKRISHNAN AP/CSE
53
MBCET
ME/CSE
6
0
6
5
2
0
6
5
6
Enter avail matrix :
1
5
2
0
Busy
Busy
Busy
Busy
Busy
Need matrix :
0000
0750
1002
0020
0642
i =0
flag =0
c =1 1532
i =1
flag =1
c =1 1532
i =2
flag =0
c =2 2886
i =3
flag =0
c =3 214118
i =4
flag =0
c =4 2141212
i =1
flag =0
c =5 3141212
Order
02341
V.GOPALAKRISHNAN AP/CSE
54
MBCET
ME/CSE
RESULT:
Thus the java program to allocate the resources for processes using bankers algorithm has
been executed successfully and the output is verified.
V.GOPALAKRISHNAN AP/CSE
55
MBCET
ME/CSE
Ex. No :10
CONCURRENT LINKEDLIST
Date :
AIM:
To write a java program to perform a concurrent Linked List.
ALGORITHM:
1. Declare all necessary variables and initialise those variables.
2. In CDApp class create a object for the class CDLinkList.
3. Create an object for the class CDApp.
4. Print the menu which has operations like add,view,search,delete,exit.
5. Get the choice that which operation you want to do.
6. Using switch case perform the operation in the menu.
7. Create an object for the class CDDetails,it maintains the details which has enter in the class
CDApp.
8. If we perform one operation then that operation is locked,if we finish that operation then the
lock will be release.
9. In add operation we can add titles and categaries, in view operation we can view the details
in the list.
10. In search operation we can search any titles that already present in the list if the details are
not present then it returns element not found.
11. In delete operation we can remove details in the list.
V.GOPALAKRISHNAN AP/CSE
56
MBCET
ME/CSE
PROGRAM:
CDApp.java
package cd;
import java.util.Scanner;
public class CDApp
{
public static CDLinkList d = new CDLinkList();
public static void main(String[] args) {
final CDApp db = new CDApp();
while (true) {
System.out.println(" MENU ");
System.out.println("1.Add new CD ");
System.out.println("2.View all CDs ");
System.out.println("3.search CD based on title ");
System.out.println("4.Delete CD entry ");
System.out.println("5.Exit");
try {
Scanner sin =new Scanner(System.in);
int choice =sin.nextInt(); //Integer.parseInt(br.readLine());
switch (choice) {
case 1:
System.out.println("Enter CD Title ");
final String title = sin.next();//br.readLine();
System.out.println("Enter CD Category ");
System.out.println("Education ");
System.out.println("Entertainment ");
System.out.println("Games ");
System.out.println("Examinations ");
System.out.println("Soft Skills ");
final String category = sin.next();//Integer.parseInt(br.readLine());
Thread one = new Thread(new Runnable() {
public void run() {
System.out.println("Thread 1 ");
db.addEntry(title, category);
V.GOPALAKRISHNAN AP/CSE
57
MBCET
ME/CSE
58
MBCET
ME/CSE
three.start();
four.start();
//
db.removeEntry(t);
break;
case 5:
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void addEntry(String tit, String cat) {
CDDetails data = new CDDetails(tit, cat);
boolean s = d.find(data);
if (s==true) {
System.out.println("CD already present");
}
else
{
d.add(data);
}
}
public void removeEntry(String tit) {
CDDetails data = new CDDetails(tit);
d.remove(data);
}
public void viewEntry(String tit) {
CDDetails data = new CDDetails(tit);
String cdEntry = d.viewEntry(data);
if (cdEntry.length() > 0) {
V.GOPALAKRISHNAN AP/CSE
59
MBCET
ME/CSE
System.out.println("CD found"+cdEntry.length());
System.out.println("Title & category:"+"\n"+ cdEntry);
}
}
public String viewEntries() {
return d.view();
}
}
CDDetails.java
package cd;
public class CDDetails
{
private String cdTitle;
private String cdCatogory;
public CDDetails(String title, String category) {
this.cdTitle = title;
this.cdCatogory = category;
}
public CDDetails(String title) {
this.cdTitle = title;
this.cdCatogory = "";
}
public void setTitle(String title) {
this.cdTitle = title;
}
public void setCategory(String category) {
this.cdCatogory = category;
}
public String getTitle() {
return cdTitle;
}
public String getCategory() {
return cdCatogory;
V.GOPALAKRISHNAN AP/CSE
60
MBCET
ME/CSE
}
public int hashCode() {
return cdTitle.hashCode();
}
public boolean equals(Object obj) {
boolean flag = false;
CDDetails cd = (CDDetails) obj;
//equals used by view entry method
if(cd.cdCatogory=="")
{
if (this.cdTitle.equals(cd.cdTitle))
flag = true;
return flag;
}
//equals used by find method
else
{
if (this.cdTitle.equals(cd.cdTitle) && this.cdCatogory.equals(cd.cdCatogory))
flag = true;
return flag;
}
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append( this.cdTitle+"\t");
buffer.append( this.cdCatogory+"\n");
return buffer.toString();
}
}
CDLinkList.java
package cd;
import java.util.concurrent.locks.*;
public class CDLinkList
{
V.GOPALAKRISHNAN AP/CSE
61
MBCET
ME/CSE
public CDLinkList() {
this.firstNode = null;
V.GOPALAKRISHNAN AP/CSE
62
MBCET
ME/CSE
this.size = 0;
}
*/
public Lock getLock() {
return lock;
}
public void setLock(Lock lock) {
this.lock = lock;
}
public void add(Object inputData) {
System.out.println("Lock in insert");
lock.lock();
ListNode curr;
ListNode node = new ListNode(inputData);
if (this.size == 0)
{
this.firstNode = node;
curr = this.firstNode;
}
else
{
curr = this.firstNode;
while (curr.getNext() != null)
{
curr = curr.getNext();
}
curr.setNext(node);
}
this.size++;
lock.unlock();
}
public void remove(Object inputData) {
System.out.println("Lock in remove");
lock.lock();
V.GOPALAKRISHNAN AP/CSE
63
MBCET
ME/CSE
ListNode curr;
ListNode prev = null;
ListNode input = new ListNode(inputData);
boolean f=false;
curr = this.firstNode;
if(curr==null)
{
System.out.println("List is empty");
}
else
{
//
while(curr!=null)
//
{
while (!curr.equals(input)) {
if (curr.getNext() == null)
break;
prev = curr;
curr = curr.getNext();
}
/*if (prev == null)
{
if(curr.equals(input))
{
this.firstNode = curr.getNext();
this.size--;
f=true;
}
else
f=false;
} */
if (prev == null && curr.equals(input))
{
if(curr.getNext()==null)
this.firstNode=null;
V.GOPALAKRISHNAN AP/CSE
64
MBCET
ME/CSE
else
this.firstNode = curr.getNext();
this.size--;
f=true;
}
else if (curr.next == null)
{
if(curr.equals(input))
{
prev.next= null;
this.size--;
f=true;
}
else
f=false;
}
else
{
prev.next = curr.getNext();
this.size--;
f=true;
}
//
curr=curr.getNext();
//
}
}
if(f==true)
System.out.println("Element Deleted");
else if(f==false)
System.out.println("Element not found");
lock.unlock();
}
public String view() {
System.out.println("Lock in view");
lock.lock();
V.GOPALAKRISHNAN AP/CSE
65
MBCET
ME/CSE
" +"Category");
System.out.println("------------------------");
while( currentNode != null )
{
Object dataObject = currentNode.getData();
buffer.append(dataObject);
currentNode = currentNode.getNext();
}
lock.unlock();
return buffer.toString();
}
else
{
StringBuffer buffer1 = new StringBuffer();
buffer1.append("List is empty");
lock.unlock();
return buffer1.toString();
}
}
public String viewEntry(Object inputData) {
System.out.println("Lock in view single entry");
lock.lock();
ListNode curr = this.firstNode;
StringBuffer buffer = new StringBuffer();
ListNode input = new ListNode(inputData);
while( curr != null )
{
while (!curr.equals(input)) {
if (curr.getNext() == null)
break;
V.GOPALAKRISHNAN AP/CSE
66
MBCET
ME/CSE
curr = curr.getNext();
}
if (curr.next == null)
{
if(this.size==1 || this.size !=1)
{
if(curr.equals(input))
{
Object dataObject = curr.getData();
buffer.append(dataObject);
}
else
{
System.out.println("Element not found");
}
}
}
else if(curr.next!=null)
{
if(curr.equals(input))
{
67
MBCET
ME/CSE
}
public boolean find(Object inputData) {
//lock.lock();
//
}
}
OUTPUT :
init:
deps-jar:
compile-single:
run-single:
MENU
1.Add new CD
2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit
1
V.GOPALAKRISHNAN AP/CSE
68
MBCET
ME/CSE
Enter CD Title
XXX
Enter CD Category
Education
Entertainment
Games
Examinations
Soft Skills
Education
Thread 1
Lock in insert
MENU
1.Add new CD
2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit
Thread 2
CD already present
1
Enter CD Title
ZZZ
Enter CD Category
Education
Entertainment
Games
Examinations
Soft Skills
Entertainment
Thread 1
Lock in insert
V.GOPALAKRISHNAN AP/CSE
69
MBCET
ME/CSE
MENU
1.Add new CD
2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit
Thread 2
CD already present
2
Lock in view
Title
Category
-----------------------XXX Education
ZZZ
Entertainment
MENU
1.Add new CD
2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit
3
Enter CD Title
XXX
Lock in view single entry
Element not found
CD found14
Title & category:
XXX Education
MENU
1.Add new CD
V.GOPALAKRISHNAN AP/CSE
70
MBCET
ME/CSE
4
Enter CD Title
ZZZ
Thread 3
Thread 4
Lock in remove
Element Deleted
MENU
1.Add new CD
2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit
Lock in remove
Element not found
5
BUILD SUCCESSFUL (total time: 12 minutes 19 seconds)
V.GOPALAKRISHNAN AP/CSE
71
MBCET
ME/CSE
RESULT:
Thus the java program to perform a concurrent Linked List has been executed successfully
and the output is verified.
V.GOPALAKRISHNAN AP/CSE
72
MBCET
ME/CSE
Ex.No :11
CONCURRENT STACK
Date :
AIM:
To write a java program to perform concurrent stack.
ALGORITHM:
1. In stack print the options 1.push ,2.pop ,3.view stack element, 4.exit for operations in
stack.Get the option in variable choice and execute using switch case.
2. If choice is 1 executed by threads. if thread1 ,then do push operation by getting an element
and store it in variable x.using run method execute thread 1 and push x into d1.If thread 2
then do pop.
3. If thread 3 then push all the elements in the stack in to d1.
4. Execeptions were catched using catch(InterruptedException e) using print StackTrace
method
5. If choice is 2 then do pop operation and remove the element at the top of the stack put it in
d1.
6. If choice is 3 then view method views the element in d1.
7. If choice is 4 then exit.
8. class StackImp is used to make Backoff with minimum delay and maximum delay.
9. Class Node the element are stored in the variable value .the null value is stored in next
variable
10. The values are returned to the stackappl class.
V.GOPALAKRISHNAN AP/CSE
73
MBCET
ME/CSE
PROGRAM:
Backoff.java
package test;
import java.util.Random;
public class Backoff {
final int minDelay, maxDelay;
int limit;
final Random random;
public Backoff(int min, int max) {
minDelay = min;
maxDelay = max;
limit = minDelay;
random = new Random();
}
public void backoff() throws InterruptedException {
int delay = random.nextInt(limit);
limit = Math.min(maxDelay, 2 * limit);
Thread.sleep(delay);
}
}
Node.java:
package test;
public class Node {
public int value;
public Node next;
public Node()
{
value =0;
next = null;
}
public Node(int val)
{
value = val;
V.GOPALAKRISHNAN AP/CSE
74
MBCET
ME/CSE
next = null;
}
}
StackApp.java:
package test;
import java.util.Scanner;
public class StackApp {
static StackImp d1 = new StackImp();
static StackApp d = new StackApp();
public static void main(String[] args) throws InterruptedException {
Scanner sin =new Scanner(System.in);
while (true) {
System.out.println(" MENU ");
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.println("3.View Stack Element");
System.out.println("4.Exit");
int choice =sin.nextInt();
switch (choice) {
case 1:
System.out.println("Enter item:");
final int x=sin.nextInt();
Thread one = new Thread(new Runnable() {
public void run() {
System.out.println("Thread 1 ");
try {
d1.push(x);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
V.GOPALAKRISHNAN AP/CSE
75
MBCET
ME/CSE
one.start();
//one.sleep(1000);
two.start();
//
three.start();
//d1.push(x);
break;
case 2:
d1.pop();
break;
case 3:
d1.view();
V.GOPALAKRISHNAN AP/CSE
76
MBCET
ME/CSE
break;
case 4:
System.exit(0);
}
}
}
}
StackImp.java:
package test;
import java.util.concurrent.atomic.AtomicReference;
public class StackImp {
AtomicReference<Node> top = new AtomicReference<Node>(null);
static final int MIN_DELAY = 1000;
static final int MAX_DELAY = 10000;
Backoff backoff = new Backoff(MIN_DELAY, MAX_DELAY);
public boolean tryPush(Node node){
Node oldTop = top.get();
node.next = oldTop;
return(top.compareAndSet(oldTop, node));
}
public void push(int value) throws InterruptedException {
Node node = new Node(value);
while (true) {
if (tryPush(node)) {
return;
} else {
backoff.backoff();
}
}
}
public Node tryPop()
{
V.GOPALAKRISHNAN AP/CSE
77
MBCET
ME/CSE
78
MBCET
ME/CSE
}
}
else
{
System.out.println("stack is empty");
}
}
}
OUTPUT :
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
1
Enter item:
20
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
Thread 2
1
Enter item:
30
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
Thread 2
1
V.GOPALAKRISHNAN AP/CSE
79
MBCET
ME/CSE
Enter item:
40
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
Thread 2
1
Enter item:
50
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
Thread 2
1
Enter item:
60
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
Thread 2
2
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
3
50
V.GOPALAKRISHNAN AP/CSE
80
MBCET
ME/CSE
40
30
20
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
BUILD SUCCESSFUL (total time : 50 seconds)
V.GOPALAKRISHNAN AP/CSE
81
MBCET
ME/CSE
RESULT:
Thus the java program to perform concurrent stack has been executed successfully and the
output is verified.
V.GOPALAKRISHNAN AP/CSE
82
MBCET
ME/CSE
Ex.No :12
CONCURRENT QUEUE
Date :
AIM:
To write a java program to perform a concurrent queue.
ALGORITHM:
1.
2.
In the empApp class create an object for QueueImp and for MyQueue.
3.
In the empApp, perform the switch case with operations like adding and deleting
emp details and viewing them.
4.
In the add operation, the threads are used to get the details of employees and add
them to the queue. Similarly, we can perform delete operations by representing any
one of the emp details. In view operation, we can view the details that are entered.
5.
The QueueImp object is used to perform Lock and Unlock operation. For this it
requires capacity to pass as a parameter.
6.
Also create a class known as ListNode with declarations for data and listnode next.
7.
In this the Wake Dequeuers are used to perform lock and to release it after
completing the operation.
8.
In MyQueue object, this operator is used to get the emp id, name and the dept. these
details are get in the form of a string.
9.
Once the emp detail is deleted, the dequeue thread is displayed and the order of
threads are rearranged and displayed when option 3 is entered.
10.
In such a way all the operations are performed as we enter the option.
V.GOPALAKRISHNAN AP/CSE
83
MBCET
ME/CSE
PROGRAM:
empApp.java
package test;
import java.util.Scanner;
public class empApp
{
//
84
MBCET
ME/CSE
85
MBCET
ME/CSE
two.sleep(5000);
System.out.println("Thread id:"+three.getId());
three.start();
three.sleep(8000);
System.out.println("Thread id:"+four.getId());
four.start();
break;
case 2:
//db.removeEntry();
Thread five = new Thread(new Runnable() {
public void run() {
try {
db.removeEntry();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
86
MBCET
ME/CSE
System.out.println("Thread id:"+five.getId());
five.start();
five.sleep(8000);
System.out.println("Thread id:"+six.getId());
six.start();
six.sleep(5000);
System.out.println("Thread id:"+seven.getId());
seven.start();
seven.sleep(5000);
break;
case 3:
String cds = db.viewEntries();
System.out.println(cds);
break;
case 4:
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void addEntry() throws InterruptedException {
Scanner sin =new Scanner(System.in);
System.out.println("Enter emp id ");
final int id=sin.nextInt();
System.out.println("Enter emp name");
final String name = sin.next();//br.readLine();
V.GOPALAKRISHNAN AP/CSE
87
MBCET
ME/CSE
88
MBCET
ME/CSE
89
MBCET
ME/CSE
90
MBCET
ME/CSE
notFullCondition.await();
Thread one = new Thread(new Runnable() {
public void run() {
System.out.println("Call dequeue by thread");
try {
deq();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
one.start();
}
ListNode e = new ListNode(x);
tail.next = tail = e;
if (size.getAndIncrement() == 0)
mustWakeDequeuers = true;
} finally {
enqLock.unlock();
}
if (mustWakeDequeuers) {
deqLock.lock();
V.GOPALAKRISHNAN AP/CSE
91
MBCET
ME/CSE
try {
notEmptyCondition.signalAll();
} finally {
deqLock.unlock();
}
}
}
public Object deq() throws InterruptedException {
Object result;
boolean mustWakeEnqueuers = true;
deqLock.lock();
try {
while (size.get() == 0)
notEmptyCondition.await();
result = head.next.data;
head = head.next;
if (size.getAndDecrement() == capacity) {
mustWakeEnqueuers = true;
}
} finally {
deqLock.unlock();
}
if (mustWakeEnqueuers) {
enqLock.lock();
try {
notFullCondition.signalAll();
} finally {
enqLock.unlock();
}
}
return result;
}
public String view()
{
V.GOPALAKRISHNAN AP/CSE
92
MBCET
ME/CSE
System.out.println("------------------------");
while( currentNode != null )
{
Object dataObject = currentNode.getData();
buffer.append(dataObject);
currentNode = currentNode.getNext();
}
return buffer.toString();
}
else
{
StringBuffer buffer1 = new StringBuffer();
buffer1.append("Queue is empty");
return buffer1.toString();
}
}
}
OUTPUT :
MENU
1.Add emp details
2. Delete emp detail
3. view
4. Exit
3
Queue is empty
MENU
1.Add emp details
2. Delete emp detail
3. view
V.GOPALAKRISHNAN AP/CSE
93
MBCET
ME/CSE
4. Exit
1
Thread id :8
Enter emp id
1
Enter emp name
XXX
Enter emp dept
CSE
Thread id :9
Enter emp id
2
Enter emp name
YYY
Enter emp dept
EEE
Thread id :10
Enter emp id
3
Enter emp name
ZZZ
Enter emp dept
ECE
Thread id :11
MENU
1.Add emp details
2. Delete emp detail
3. view
4. Exit
Dequeue thread
3
Id
Name
Dept
-------------------------------------1
XXX
CSE
V.GOPALAKRISHNAN AP/CSE
94
MBCET
ME/CSE
YYY EEE
ZZZ
ECE
MENU
1.Add emp details
2. Delete emp detail
3. view
4. Exit
4
V.GOPALAKRISHNAN AP/CSE
95
MBCET
ME/CSE
RESULT:
Thus the java program to perform concurrent queue has been executed successfully and the output
is verified.
V.GOPALAKRISHNAN AP/CSE
96