You are on page 1of 62

CP7111

L T P C

ADVANCED DATA STRUCTURES LABORATORY


0042

OBJECTIVES:

To learn to implement iterative and recursive algorithms.


To learn to design and implement algorithms using hill climbing and dynamic programming
techniques.
To learn to implement shared and concurrent objects.
To learn to implement concurrent data structures.

LAB EXERCISES:
Each student has to work individually on assigned lab exercises. Lab sessions could be
scheduled as one contiguous four-hour session per week or two two-hour sessions per week.
There will be about 15 exercises in a semester. It is recommended that all implementations are
carried out in Java. If C or C++ has to be used, then the threads library will be required for
concurrency. Exercises should be designed to cover the following topics:

Implementation of graph search algorithms.


Implementation and application of network flow and linear programming problems.
Implementation of algorithms using the hill climbing and dynamic programming design
techniques.
Implementation of recursive backtracking algorithms.
Implementation of randomized algorithms.
Implementation of various locking and synchronization mechanisms for concurrent linked
lists, concurrent queues, and concurrent stacks.
Developing applications involving concurrency.

TOTAL :60 PERIODS

Ex No: 1

IMPLEMENTATION OF GRAPH SEARCH ALGORITHMS


(a) Implementation of Breadth First Search

AIM:
To write a program to implement Breadth First Search.
ALGORITHIM:
1. Start the process.
2. Visits all the vertices and edges of tree. It uses the principle of queue.
3. In graph theory, breadth-first search (BFS) is a strategy for searching in a graph when
search is limited to essentially two operations:
(a) Visit and inspect a node of a graph;
(b) Gain access to visit the nodes that neighbor the currently visited node.
4. The BFS begins at a root node and inspects all the neighboring nodes.
5. Then for each of those neighbor nodes in turn, it inspects their neighbor nodes which
were unvisited, and so on.
6. If the element sought is found in this node, quit the search and return a result.
7. Stop the process.

PROGRAM:
import java.io.*;
class bfs1
{
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<10; i++)
{
m[i] = 0;
}
System.out.println("\n\nEnter 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("\nOrder of accessed nodes : \n");
q[0] = 0; m[0] = 1;
int u;
int node=1;
int beg1=1, 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:
E:\java1>javac bfs1.java
E:\java1>java bfs1
No. of vertices :
4
Enter 1 if edge is present, 0 if not
Edge between 1 and 1:
0
Edge between 1 and 2:
1
Edge between 1 and 3:
1
Edge between 1 and 4:
0
Edge between 2 and 2:
0
Edge between 2 and 3:
0
Edge between 2 and 4:
1
Edge between 3 and 3:
0
Edge between 3 and 4:
1
Edge between 4 and 4:
0

Order of accessed nodes :


1
2
3
4

RESULT:
Thus the source code was developed and executed successfully.
(b) Implementation of Depth First Search
AIM:
To write a program to implement Depth First Search.

ALGORITHIM:
1.
2.
3.
4.
5.

Start the process.


Push the root node in the Stack.
Loop until stack is empty.
Seek the node of the stack.
If the node has unvisited child nodes, get the unvisited child node, mark it as
traversed and push it on stack.
6. If the node does not have any unvisited child nodes, pop the node from the stack.
7. Stop the process.

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);
}
public static void main(String args[]) throws IOException
{
int n, i, j;
System.out.println("No. of vertices : ");
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
n =Integer.parseInt(br.readLine());
int m[]= new int[n];
int a[][] = new int[n][n];
for (i=0; i<n; i++)
{
m[i] = 0;
}
System.out.println("\n\nEnter 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 " +
a[i][j] =Integer.parseInt(br.readLine());
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:

(j+1)+ " : ");

E:\java1>javac dfs1.java
E:\java1>java dfs
No. of vertices :
4
Enter 1 if edge is present, 0 if not
Edge between 1 and 1 :
0
Edge between 1 and 2 :
1
Edge between 1 and 3 :
1
Edge between 1 and 4 :
0
Edge between 2 and 2 :
0
Edge between 2 and 3 :
0
Edge between 2 and 4 :
1
Edge between 3 and 3 :
0
Edge between 3 and 4 :
1
Edge between 4 and 4 :
0

Order of accessed nodes :


1
2
4
3

RESULT:
Thus the source code was developed and executed successfully.
(c) Implementation Of Dijkstras Algorithm
AIM:
To write a program to implement Dijkstras Algorithm.
ALGORITHIM:
1. Start the process.
2. Initializing and declaring of variables.
3. Enter the number of vertices.
4. Enter the source and destination
5. Insert the element is priority queue.
6. Delete the element in the priority queue.
7. Stop the process.

PROGRAM:
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Vertex implements Comparable<Vertex>
{
public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;
public Vertex(String argName) { name = argName; }
public String toString() { return name; }
public int compareTo(Vertex other)

{
return Double.compare(minDistance, other.minDistance);
}
}
class Edge
{
public final Vertex target;
public final double weight;
public Edge(Vertex argTarget, double argWeight)
{ target = argTarget; weight = argWeight; }
}
public class Dijkstra
{
public static void computePaths(Vertex source)
{
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies)
{
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU ;
v.previous = u;
vertexQueue.add(v);
}
}
}
}
public static List<Vertex> getShortestPathTo(Vertex target)

{
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}

public static void main(String[] args)


{
Vertex v0 = new Vertex("Redvile");
Vertex v1 = new Vertex("Blueville");
Vertex v2 = new Vertex("Greenville");
Vertex v3 = new Vertex("Orangeville");
Vertex v4 = new Vertex("Purpleville");
v0.adjacencies = new Edge[]{ new Edge(v1, 5),
new Edge(v2, 10),
new Edge(v3, 8) };
v1.adjacencies = new Edge[]{ new Edge(v0, 5),
new Edge(v2, 3),
new Edge(v4, 7) };
v2.adjacencies = new Edge[]{ new Edge(v0, 10),
new Edge(v1, 3) };
v3.adjacencies = new Edge[]{ new Edge(v0, 8),
new Edge(v4, 2) };
v4.adjacencies = new Edge[]{ new Edge(v1, 7),
new Edge(v3, 2) };
Vertex[] vertices = { v0, v1, v2, v3, v4 };
computePaths(v0);
for (Vertex v : vertices)
{
System.out.println("Distance to " + v + ": " + v.minDistance);
List<Vertex> path = getShortestPathTo(v);
System.out.println("Path: " + path);
}
}
}

OUTPUT:
E:\java1> javac Dijkstra.java
E:\java1> java Dijkstra
Distance to Redvile: 0.0
Path: [Redvile]
Distance to Blueville: 5.0
Path: [Redvile, Blueville]
Distance to Greenville: 8.0
Path: [Redvile, Blueville, Greenville]
Distance to Orangeville: 8.0
Path: [Redvile, Orangeville]
Distance to Purpleville: 10.0
Path: [Redvile, Orangeville, Purpleville]

RESULT:
Thus the source code was developed and executed successfully.
Ex No: 2

IMPLEMENTATION AND APPLICATION OF NETWORK FLOW AND


LINEAR PROGRAMMING PROBLEMS
(a) Implementation of Linear Programming Problems

AIM:
To write a program to implement Linear Programming Problems.
ALGORITHIM:
1.
2.
3.
4.
5.
6.
7.

Start the Process


Import all the necessary library files.
Initialize variables
Open the required files with read write mode
Declare the equations and frame it by using users input
Process and store the data in the corresponding files
End of the program

PROGRAM:
import java.io.*;
import java.text.*;
import java.awt.*;
import java.awt.event.ActionEvent.*;
import java.awt.event.WindowEvent;
import java.lang.Math.*;
import java.lang.Character;
import java.lang.Float;
import java.lang.Integer;
import java.lang.Object;
import java.lang.Boolean;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.RandomAccess;
public class Linear2 extends Frame
{

static final int M=15;


static final int N=30;
static double PENALTY =-900.00;
static final double EPS=0.00001;
static int i,j;
static char res_in_file;
static char yn;
//readfile1
//writefile3
//result2
// resultfile4
static RandomAccessFile raf1,raf2,raf3,raf4;
static int mm;
static int k;
static int m;
static int n;
static int kr,kc,kf;
float top[];
float base[];
float left[];
char sign[];
int basic[];
float x[][];
float keyNo;
static float obj;
public void readData(){
int i=0;
for(j=0;j < m; j++){
for( int j = 0; j < m; j++ )
{
if( x[ j ]== null )
System.out.print( "(null)" );
else
{
for( j = 0; j < x[i].length; j++ )
System.out.print( x[ i ][ j ] + " " );
//System.out.print( );
}
}
System.out.print(" \n x[i][j]"+ " ");
System.out.print(" \n sign[i]"+ " ");

System.out.print(" \n left[i]"+ " ");


}
}
public void addSlack()
{
int i;
for(i=0;i<m;i++)
{
if(sign[i] == '<'|| sign[i] == '>')
{
n++;
for(int i1=0;i1<m;i1++)
x[i1][n-1]=0;
if(sign[i] == '<')
{
x[i][n-1]=1; top[n-1]=0;
basic[i]=n-1;
}
else
{
x[i][n-1]= -1;
top[n-1]= 0;
}
}
}
}
public void addArti()
{
int i;
for(i=0;i<n;i++)
if (sign[i] == '='|| sign[i] == '>')
{
n++;
for(int i1=0;i1<m;i1++)
x[i][n-1]=0;
x[i][n-1]=-900;
top[n-1] =-900;
basic[i]= n-1;
}
}
public void findbase()
{

int i,j;
for(j=0;j<n;j++)
{
base[j]=0;
for(i=0;i<m;i++)
base[j] += x[i][j] * top[basic[i]];
base[j]= base[j]-top[j];
}
}
public void display()
{
int i,j;
for(j=0;j<n;j++)
System.out.println("\n top[j]"+ j);
for(i=0;i<m;i++)
{
System.out.print("\n top[basic[i]]" + i);
System.out.print("\n basic[i])+1"+ i);
System.out.print("\n left[i]"+ i);
for(j=0;j<n;j++)
System.out.println("\n x[i][j] "+ j);
for(j=0;j<n;j++)
System.out.println("\n base[j]"+j);
}
}
public int keyRow(int k)
{
int i; float ratio; float min =100000; int l= - 1;
for(i=0;i<m;i++)
{
if(x[i][k] < EPS && left[i] > EPS)
continue;
else
ratio = left[i]/x[i][k];
if(ratio < -EPS)
continue;
else
if(left[i]/x[i][k] < min)
{
min = left[i]/x[i][k];
l=i++;

}
}
if(l == -1)
{
System.out.println("\n UnboundedSolution");
}
return 1;
}
public int keyColumn()
{
int j;
float min =0;
int l = -1;
for(j=0;j<n;j++)
{
if(base[j] < min)
{
min = base[j];
l=j;
}
}
return 1;
}
public void modify(int kr,int kc)
{
int i,j; float keyNo;
float temp[]=new float[M];
for(i=0;i<m;i++)
temp[i] = x[i][kc];
basic[kr]=kc;
keyNo=x[kr][kc];
for(j=0;j<n;j++)
x[kr][j]=x[kr][j]/keyNo;
left[kr]=left[kr]/keyNo;
for(i=0;i<m;i++)
{
if(i== kr)
continue;
left[i]=left[i]-left[kr] * temp[i];
}
for(i=0;i<m;i++)

{
if(i==kr)
continue;
else
for(j=0;j<n;j++)
x[i][j]=x[i][j]- temp[i] * x[kr][j];
}
obj=00.0f;
for (i=0;i<m;i++)
obj=obj+top[basic[i]] * left[i];
}
public int result()throws Exception
{
int i=0;
int feasible=1;
{
RandomAccessFile raf3 = new RandomAccessFile("myfile3.txt","rw");
raf3.seek(raf3.length());
for (i=0;i<m;i++)
obj=obj+top[basic[i]] * left[i];
for(i=0;i<m;i++)
if((top[basic[i]] < (PENALTY +0.01) && left[i] > EPS))
{
if(false);
raf3.writeFloat(obj);
System.out.print("\n OptimalValue of Objective function " + obj );
break;
}
if(true)
{
for(i=0;i<m;i++)
{
raf3.writeInt(i);
System.out.print(" \n [i]+1"+ " ");
System.out.print("\n [i]"+ " ");
}
if(res_in_file == 'y')
{
for(i=0;i<m;i++)
{
obj=basic[i]+1;

}
}else{
if(res_in_file == 'Y')
{
for(i=0;i<m;i++)
{
obj=left[i];
}
raf3.writeFloat(obj);
}
System.out.print("Solution is infeasible");
}
}
return (int)obj;
}
}

public void readFile() throws Exception


{
RandomAccessFile raf1= new RandomAccessFile("myfile1.txt","rw");
raf1.seek(raf1.length());
for(int i=0; i < raf1.length();i++)
{
try
{
int mm=raf1.readInt();
k=raf1.readInt();
m=raf1.readInt();
n=k;
for(j=0;j<k;j++)
{
top[j]= j;
if(mm==2)
top[j]=0-top[j];
}
for(i=0;i<m;i++)
{
for(j=0;j<k;j++)
top[j] = raf1.readInt();
do{

sign[i]=raf1.readChar();
left[i]=raf1.readInt();
}while(true);
}
System.out.print((int)mm);
}
catch(EOFException e)
{
break;
}
}
}
public void writeFile()
{
int i,j;
try
{
RandomAccessFile raf2= new RandomAccessFile("myfile2.txt","rw");
raf2.seek(raf1.length());
while(raf1.getFilePointer()< raf1.length())
raf2.writeInt(mm);
raf2.writeInt(k);
raf2.writeInt(m);
n=k;
if(mm==1){
for(j=0;j<k;j++)
top[j]=j;
for (j=0;j<top.length;j++)
{
System.out.print((int)j);
}
}
else
for(i=0;i<m;i++)
for (j=0;j<k;j++){
x[i][j]=i;
}
for(i=0;i<x.length;i++){
System.out.print((int)i);
}
for(i=0;i<sign.length;i++)

{
raf2.writeInt(i);
System.out.print((int)i);
}
left[i]=i;
for(i=0;i<left.length;i++)
{
raf2.writeInt(i);
System.out.print((int)i);
}
raf2.close(); }
catch(Exception e)
{}
}

public void resultFile()


{
int i,j=0;
try
{
RandomAccessFile raf4 = new RandomAccessFile("myfile4.txt","rw");
raf4.seek(raf4.length());
while(raf4.getFilePointer() < raf4.length())
{
{
i=raf4.readInt();
}
}
for(j=0;j<n;j++)
top[j]=j;
for(j=0;j<top.length;j++){
raf4.writeInt(j);
raf4.seek(0);
j=raf4.readInt();
System.out.print((int)j);
}
for(j=0;j<n;j++)
for(i=0;i<m;i++)
{
top[basic[i]] = i+1;

for(i=0;i<top.length;i++)
for(i=0;i<basic.length;i++)
{
raf4.writeInt(i);
System.out.print((int)i);
}
for(j=0;j<n;j++)
x[i][j]=i;
for(i=0;i<x.length;i++)
for(j=0;j<x.length;j++)
{
raf4.writeInt(i);
System.out.print((int)i);
}
for(j=0;j<n;j++)
obj=j;
{
raf4.writeFloat(obj);
System.out.print((int)obj);
}
for(j=0;j<n;j++)
base[j]=j;
{
raf4.writeFloat(obj);
System.out.print((int)j);
}
}
}
catch(Exception e)
{};
}
public static void main(String args[])throws IllegalAccessException,Exception
{
//RandomAccessFile raf1;
raf1= new RandomAccessFile("myfile1.txt","rw");
// RandomAccessFile raf2;
raf2= new RandomAccessFile("myfile2.txt","rw");
//RandomAccessFile raf3;
raf3= new RandomAccessFile("myfile3.txt","rw");
//RandomAccessFile raf4;
raf4= new RandomAccessFile("myfile4.txt","rw");

Frame fme = new Frame();


fme.addWindowListener(new WindowAdapter()
{
public void windowClosed(WindowEvent e)
{System.exit(0);}
});
Linear2 lp;
lp= new Linear2();
int kc=0;
int kr=0;
int kf=0;
//char fres[]={15};
String s1;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
s1=br.readLine();
System.out.print("\n Linear2 ");
s1=br.readLine();
System.out.print("\n Enter no of Objective variables (k = of the maxy/mini eqn): " + " ");
s1=br.readLine();
System.out.print("\n Enter the coef of Objective Functions :( coef of maxy/mini eqn) :"+
" ");
s1=br.readLine();
System.out.print("\n Enter no of Constraints (m): " + " ");
s1=br.readLine();
System.out.print("\n Enter the Constraints :( coef of constraints from eqns for both left
and right sides) "+ " ");
s1=br.readLine();
System.out.print("\n Enter > for >_ and < for _<: "+ " ");
s1=br.readLine();
//System.out.println("\n Read data from Key board (1) or File(2):" + " ");
// s1=br.readLine();
System.out.print("\n File name to write result (myfile2):"+" ");
s1=br.readLine();
System.out.print("\n Do you want to maximise(1) or minimize(2) (mm):" + " ");
s1=br.readLine();
for(j=0;j<k;j++)
{
if(mm==2)
System.out.print(" \n top[j]=0-top[j]"+ j +"");
else
System.out.print(" \ntop[j]"+ j+" ");

}
System.out.print("\n File name to read (myfile1):"+ " ");
s1=br.readLine();
System.out.print("\n Enter data from keyboard (1) or file(2)(kf):" + " ");
s1=br.readLine();
if(kf==1)
{
lp.readData();
}
System.out.print("\n Output required in file (yn):" + " ");
s1=br.readLine();
if( yn =='y' || yn == 'Y')
{
lp.writeFile();
}
System.out.print("\n Store data in disc file (y/n):"+ " ");
s1=br.readLine();
if(res_in_file == 'y' || res_in_file =='Y')
{
lp.readFile();
}
lp.addSlack();
lp.addArti();
lp.findbase();
lp.display();
lp.resultFile();
i=1;
{
kc= lp.keyColumn();
if(kc == -1)
s1=br.readLine();
System.out.print(" Linear2 " + i);
s1=br.readLine();
System.out.print("\n ***********\n");
s1=br.readLine();
System.out.print("\n KeyColumn : " + kc);
if(res_in_file == 'Y'){
lp.resultFile();
lp.keyRow(kc);
kr=lp.keyRow(kc);
}

s1=br.readLine();
System.out.print("\n KeyRow: " + kr);
lp.modify(kr,kc);
lp.findbase();
lp.display();
i++;
}
lp.result();
}
}
import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}

OUTPUT:
C:\Program Files\Java\jdk1.6.0_24\bin>javac LinearSearch.java
C:\Program Files\Java\jdk1.6.0_24\bin>java LinearSearch
Enter number of elements
5
Enter 5 integers
52
61
3
81
35
Enter value to find
3
3 is present at location 3.

RESULT:
Thus the source code was developed and executed successfully.
(b)Network Flow
AIM:
To write a program to implement Network flow.
ALGORITHIM:
1.
2.
3.
4.
5.
6.
7.
8.
9.

Start the program


Enter the number of nodes in graph
Enter the graph matrix
Enter the source of the graph
Enter the sink of the graph
Process the program by using queue and check the path flow
Find the maximum flow in the graph
Find the minimum cut set in the graph
End of the program.

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;
public class NetworkFlowProb
{
private int[] parent;
private Queue<Integer> queue;
private int numberOfVertices;
private boolean[] visited;
private Set<Pair> cutSet;
private ArrayList<Integer> reachable;
private ArrayList<Integer> unreachable;
public NetworkFlowProb (int numberOfVertices)
{
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>();
}
public boolean bfs (int source, int goal, int graph[][])
{
boolean pathFound = false;

int destination, element;


for (int vertex = 1; vertex <= numberOfVertices; vertex++)
{
parent[vertex] = -1;
visited[vertex] = false;
}
queue.add(source);
parent[source] = -1;
visited[source] = true;
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;
}
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++)
{
residualGraph[sourceVertex][destinationVertex] = graph[sourceVertex]
[destinationVertex];
}
}
/*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;
}
/*calculate the cut set*/
for (int vertex = 1; vertex <= numberOfVertices; vertex++)
{
if (bfs(source, vertex, residualGraph))
{
reachable.add(vertex);
}
else
{
unreachable.add(vertex);
}
}
for (int i = 0; i < reachable.size(); i++)
{
for (int j = 0; j < unreachable.size(); j++)
{
if (graph[reachable.get(i)][unreachable.get(j)] > 0)
{
cutSet.add (new Pair(reachable.get(i), unreachable.get(j)));
}

}
}
return maxFlow;
}
public void printCutSet ()
{
Iterator<Pair> iterator = cutSet.iterator();
while (iterator.hasNext())
{
Pair pair = iterator.next();
System.out.println(pair.source + "-" + pair.destination);
}
}
public static void main (String...arg)
{
int[][] graph;
int numberOfNodes;
int source;
int sink;
int maxFlow;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of nodes");
numberOfNodes = scanner.nextInt();
graph = new int[numberOfNodes + 1][numberOfNodes + 1];
System.out.println("Enter the graph matrix");
for (int sourceVertex = 1; sourceVertex <= numberOfNodes; sourceVertex++)
{
for (int destinationVertex = 1; destinationVertex <= numberOfNodes;
destinationVertex++)
{
graph[sourceVertex][destinationVertex] = scanner.nextInt();
}
}
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)
{
this.source = source;
this.destination = destination;
}
public Pair()
{
}
}

OUTPUT:
$javac NetworkFlowProb.java
$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
0 0 0 7 0 4
0 0 0 0 0 0
Enter the source of the graph
1
Enter the sink of the graph
6
The Max flow in the graph is 23

The Minimum Cut Set in the Graph is


2-4
5-6
5-4

RESULT:
Thus the source code was developed and executed successfully.

Ex No:3

IMPLEMENTATION OF ALGORITHMS USING THE HILL CLIMBING


AND DYNAMIC PROGRAMMING DESIGN TECHNIQUES.
(a) Implementation of 0/1 Knapsack Using Dynamic Programming

AIM:
To write a program to implement 0/1 knapsack using dynamic programming.
ALGORITHIM:
1.
2.
3.
4.
5.
6.
7.

Start the program


Declare the variables
Enter the number of objects available
Enter the weight and profit for every item
Enter the capacity of sack
Find the optimal solution based on capacity, profit and weight.
Stop the program.

PROGRAM:
import java.util.*;
import java.io.*;
import java.lang.*;
public class Knapsack01
{
static int n=5, W;
static obj st[];
public static BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
static class obj{
int weight;
int profit;
}
public static void main(String args[]) throws IOException{
int i=0;
System.out.println("Knap Sack Problem\n------------------\n");
System.out.print("Enter total number of objects: ");
n = Integer.parseInt( br.readLine() );
System.out.print("Enter the maximum weight sack can take: ");
W = Integer.parseInt( br.readLine() );
st = new obj[n+1];
st[0] = new obj();
st[0].weight = st[0].profit = 0;

for(i=1; i<=n; i++)


{
st[i] = new obj();
System.out.print("For Object "+(i)+" :-\n\tWeight: ");
st[i].weight = Integer.parseInt(br.readLine());
System.out.print("\tProfit: ");
st[i].profit = Integer.parseInt(br.readLine());
}
System.out.print("\nOptimal Solution is : ");
simple_fill();
}
static void simple_fill() {
int [][]s = new int[n+1][W+1];
for (int w = 0; w<= W; w++) s[0][w] = 0;
for(int i=0; i<=n; i++) s[i][0]=0;
for(int i=1; i<=n; i++)
for (int w = 0; w<= W; w++)
if (st[i].weight <= w)
{
if (st[i].profit + s[i-1][w-st[i].weight] > s[i-1][w])
s[i][w] = st[i].profit + s[i-1][w- st[i].weight];
else
s[i][w] = s[i-1][w];
}
else
s[i][w] = s[i-1][w];
int i = n;
int k = W;
int prof = 0;
System.out.println("\n\nITEM\t\tWEIGHT\t\tPROFIT\n");
while((i>0)&&(k>0))
{
if (s[i][k] != s[i-1][k])
{
System.out.println(i+"\t\t"+st[i].weight+"\t\t Rs."+st[i].profit);
k = k - st[i].weight;
prof += st[i].profit;
}
i--;
}
System.out.print(" \nIt will yield a profit of Rs."+ prof);

}
}
OUTPUT:
C:\>set path=C:\Program Files\Java\jdk1.6.0_02\bin
C:\Users\sen\Documents>javac Knapsack01.java
C:\Users\sen\Documents>java Knapsack01
Knap Sack Problem
-----------------Enter total number of objects: 3
Enter the maximum weight sack can take: 10

For Object 1 :Weight: 4


Profit: 5
For Object 2 :Weight: 3
Profit: 7
For Object 3 :Weight: 2
Profit: 4
Optimal Solution is :
ITEM
3

WEIGHT
2

PROFIT
Rs.4

Rs.7

Rs.5

It will yield a profit of Rs.16

RESULT:
Thus the source code was developed and executed successfully.
(b) Travelling Sales Man Problem

AIM:
To write a program to implement travelling sales man problem using hill climbing method.
ALGORITHIM:
1.
2.
3.
4.
5.
6.
7.
8.

Start theprogram
Import the exception and scanner library files
Enter the number of nodes in the graph
Enter the adjacency matrix for the corresponding nodes
Find the nearest neighbour node by using scanner keyword in the adjacency matrix
By using min and max value find the visiting procedure for cities.
Close the scanner
End of the program.

PROGRAM:

import java.util.InputMismatchException;

import java.util.Scanner;
import java.util.Stack;
public class TSPNearestNeighbour
{
private int numberOfNodes;
private Stack<Integer> stack;
public TSPNearestNeighbour()
{
stack = new Stack<Integer>();
}
public void tsp(int adjacencyMatrix[][])
{
numberOfNodes = adjacencyMatrix[1].length - 1;
int[] visited = new int[numberOfNodes + 1];
visited[1] = 1;
stack.push(1);
int element, dst = 0, i;
int min = Integer.MAX_VALUE;
boolean minFlag = false;
System.out.print(1 + "\t");
while (!stack.isEmpty())
{
element = stack.peek();
i = 1;
min = Integer.MAX_VALUE;
while (i <= numberOfNodes)
{
if (adjacencyMatrix[element][i] > 1 && visited[i] == 0)
{
if (min > adjacencyMatrix[element][i])
{
min = adjacencyMatrix[element][i];
dst = i;
minFlag = true;
}
}

i++;
}
if (minFlag)
{
visited[dst] = 1;
stack.push(dst);
System.out.print(dst + "\t");
minFlag = false;
continue;
}
stack.pop();
}
}
public static void main(String... arg)
{
int number_of_nodes;
Scanner scanner = null;
try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
adjacency_matrix[i][j] = scanner.nextInt();
}
}
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
{
adjacency_matrix[j][i] = 1;
}
}

}
System.out.println("the citys are visited as follows");
TSPNearestNeighbour tspNearestNeighbour = new TSPNearestNeighbour();
tspNearestNeighbour.tsp(adjacency_matrix);
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
scanner.close();
}
}
OUTPUT:
$javac TSPNearestNeighbour.java
$java TSPNearestNeighbour
Enter the number of nodes in the graph
9
Enter the adjacency matrix
000 374 200 223 108 178 252 285 240 356
374 000 255 166 433 199 135 095 136 017
200 255 000 128 277 128 180 160 131 247
223 166 128 000 430 047 052 084 040 155
108 433 277 430 000 453 478 344 389 423
178 199 128 047 453 000 091 110 064 181
252 135 180 052 478 091 000 114 083 117
285 095 160 084 344 110 114 000 047 078
240 136 131 040 389 064 083 047 000 118
356 017 247 155 423 181 117 078 118 000
the citys are visited as follows
1
5
3
2
9
7
4

RESULT:
Thus the source code was developed and executed successfully.
Ex No: 4 IMPLEMENTATION OF RECURSIVE BACKTRACKING ALGORITHMS.
(a) Implementation of Eight Queens Problem
AIM:
To write a program to implement Eight Queens Problem.

ALGORITHIM:
1. Start in the leftmost column
2. If all queens are placed return true
3. Try all rows in the current column. Do following for every tried row.
a) If the queen can be placed safely in this row then mark this [row, column] as part of the
solution and recursively check if placing queen here leads to a solution.
b) If placing queen in [row, column] leads to a solution then return true.
c) If placing queen doesn't lead to a solution then umark this [row, column] (Backtrack) and
go to step (a) to try other rows.
4. If all rows have been tried and nothing worked, return false to trigger backtracking.

PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.Math;

class queen extends JPanel {


static int n=0;
static int [] x;
static ChessPanel [] [] boxes;
static ImageIcon queen = new ImageIcon ("queen.gif");
static int queensCount=0;
queen (){
x = new int [n];
boxes = new ChessPanel[n][n];
setLayout(new GridLayout(n, n));
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
boxes [i][j] = new ChessPanel ();
add(boxes[i][j]);
}
}
setBackground();
for(int i=0; i<n; i++)
x[i] = -1;
}
void setBackground(){
for (int i=0; i<n;i++)
for (int j=0; j<n; j++)
if ((i+1)%2==0 && j%2==0||(j+1)%2==0 && i%2==0)
boxes[i][j].setBackground(new Color( 251, 201, 159 ));
else boxes[i][j].setBackground(new Color( 209, 139, 71 ));
}
static boolean placeQueen(int k, int num){
int i =0;
for(; i<num; i++)
{
if (place(k, i))
{
x[k] = i;
if(k == num-1)
return true;
if(placeQueen(k+1, num) == false)
{
x[k] = -1;
continue;
}
else
break;

}
}
if((x[k] == -1) && (i == num))
return false;
else
return true;
}
static boolean place(int k, int i)
{
for(int j=0; j<=k; j++)
if((x[j] == i) || (Math.abs(x[j] - i) == Math.abs(j-k)))
return false;
return true;
}
class ChessPanel extends JPanel {
ImageIcon icon = new ImageIcon("");
public ChessPanel (){
super(null);
}
public void paintComponent (Graphics g){
super.paintComponent (g);
icon.paintIcon(this, g, 15, 15);
}
void setIcon (ImageIcon icon){
this.icon = icon;
}
}
public static void main (String [] args) throws IOException{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the value of N: ");
n = Integer.parseInt(br.readLine());
JFrame frame = new JFrame(n + " Queens Solution");
queen board = new queen();
frame.add(board);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if(placeQueen(queensCount, n) == false)
System.out.println("Sorry No Solution Available");
else
{
for(int i=0; i<n; i++)
boxes[i][x[i]].setIcon(queen);
frame.setVisible(true);
}
}
}

OUTPUT:
E:\java1>javac queen.java
E:\java1>java queen
Enter the value of N: 8

RESULT:
Thus the source code was developed and executed successfully.
(b)Graph Colouring
AIM:
To write a program to implement graph colouring.
ALGORITHM:
1.
2.
3.
4.
5.
6.

Start the program


Enter the number of vertices
If edges exist between two vertices enter 1 or else 0
Enter the color available.
Arrange the graph colors as beside adjacent vertices should not have same color.
Stop the program.

PROGRAM:
import java.io.*;
public class GraphColoring
{ static int [][] G; static int [] x; static int n, m;
static boolean found = false;
public static BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException
{
System.out.println("\t\t\t\tGRAPH COLORING");
System.out.print("\nEnter the number of the vertices: ");
n = Integer.parseInt(br.readLine());
G = new int[n+1][n+1]; x = new int[n+1];
System.out.print("\nIf edge between the following vertices enter 1 else 0:\n");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if((i!=j)&&(i<j))
{

System.out.print(i+" and "+j+": ");


G[j][i]=G[i][j] = Integer.parseInt(br.readLine());
}
if(i==j)
G[i][j]=0;
}
}
System.out.print("\nEnter the number of colors available: ");
m = Integer.parseInt(br.readLine());
System.out.println("\nSolution:");
mColoring(1);
if (found == false)
System.out.println("No Solution possible!");
}
static void mColoring(int k)
{
while(true)
{
NextValue(k);
if(x[k] == 0)
return;
if(k == n)
{
for(int i=1; i<=k;i++)
System.out.print(x[i]+" ");
System.out.println();
found = true;
return;
}
else
mColoring(k+1);
}
}
static void NextValue(int k)
{
int j;
while(true)
{
x[k] = (x[k]+1)%(m+1);
if(x[k]==0)
return;
for(j=1; j<=n; j++)
if( (G[k][j] != 0) && (x[k] == x[j]) )
break;
if(j == n+1)
return;

}
}
}
OUTPUT:
C:\Users\sen\Documents>javac GraphColoring.java
C:\Users\sen\Documents>java GraphColoring
GRAPH COLORING
Enter the number of the vertices: 3
If edge between the following vertices enter 1 else 0:
1 and 2: 2
1 and 3: 0
2 and 3: 1
Enter the number of colors available: 3
Solution:
121
132
213
321
RESULT:
Thus the source code was developed and executed successfully.
Ex No: 5

IMPLEMENTATION OF RANDOMIZED ALGORITHMS

AIM:
To write a program to implement randomized algorithms.
ALGORITHM:
1. Start the program
2. Import random utility
3. Use log and random keywords to generate random numbers
4. Follow the procedure for following programs
(a) Display random numbers between 0 to 99
(b) Get a range by using start and end parameter and then generate the random
number between the ranges
(c) Find the mean,variance and by using Gaussian distribution generate the random
numbers
(d) (i) get the elements to be sorted
(ii) find the pivot and partition the elements as left and right
(iii) By using java.lang.math.random() *99,sort the elements.
5. End of the program

PROGRAM:
Example 1 :
import java.util.Random;
/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
public static final void main(String... aArgs){
log("Generating 10 random integers in range 0..99.");
//note a single Random object is reused here
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx){
int randomInt = randomGenerator.nextInt(100);
log("Generated : " + randomInt);
}
log("Done.");
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}

OUTPUT:
Generating 10 random integers in range 0..99.
Generated : 44
Generated : 81
Generated : 69
Generated : 31
Generated : 10
Generated : 64
Generated : 74
Generated : 57
Generated : 56
Generated : 93
Done.

Example 2:
This example generates random integers in a specific range.
import java.util.Random;
/** Generate random integers in a certain range. */
public final class RandomRange {
public static final void main(String... aArgs){
log("Generating random integers in the range 1..10.");
int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1; idx <= 10; ++idx){
showRandomInteger(START, END, random);
}
log("Done.");
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems

long range = (long)aEnd - (long)aStart + 1;


// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
OUTPUT:
An example run of this class:
Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.
Example 3:
This example generates Prime Number using Fermats little theorem
import java.io.*;
import java.util.Random;
import java.math.BigInteger;
import java.util.Scanner;
public class Ferma
{
public static void main(String[] args)
{
Random r=new Random();
Scanner s=new Scanner(System.in);
BigInteger p,y;

System.out.println("enter p");
p=s.nextBigInteger();
for(int i=0;i<5;i++)
{
int r2=r.nextInt(99);
BigInteger x=BigInteger.valueOf(r2);
while(true)
{
BigInteger b=x.gcd(p); //chck gcd(x,p)
if(b.equals(BigInteger.ONE))
{
break;
}
r2++;
}
BigInteger a=new BigInteger(""+r2); //store the final value of r2 as a
BigInteger z=p.subtract(BigInteger.ONE); //p-1
y=a.modPow(z, p); //a^p-1/p
if(y.equals(BigInteger.ONE))
{
System.out.println("prime number");
break;
}else
{
System.out.println("not prime");
break;
}
}
}
}
OUTPUT:
enter p
563
prime number
Example 4:

Implementation Of Randomized Quick Sort

PROGRAM:
// randomizedQuickSort.java

import java.util.*;
// imported so that Random class can be used
class ArrayIns
{
private long[] theArray;
// ref to array theArray
private int nElems;
// number of data items
//-------------------------------------------------------------public ArrayIns(int max)
// constructor
{
theArray = new long[max];
// create the array
nElems = 0;
// no items yet
}
//-------------------------------------------------------------public void insert(long value) // put element into array
{
theArray[nElems] = value;
// insert it
nElems++;
// increment size
}
//-------------------------------------------------------------public void display()
// displays array contents
{
System.out.print("A=");
for(int j=0; j<nElems; j++) // for each element,
System.out.print(theArray[j] + " "); // display it
System.out.println("");
}
//-------------------------------------------------------------public void quickSort()
{
recQuickSort(0, nElems-1);
}
//-------------------------------------------------------------public void recQuickSort(int left, int right)
{
if(right-left <= 0)
// if size <= 1,
return;
// already sorted
else
// size is 2 or larger
{
// The following three lines of code ensure that an
// element chosen uniformly at random from
// theArray[left..right] is used as the pivot.

Random rand = new Random();


int pivotIndex = left + rand.nextInt(right-left+1);
swap(pivotIndex, right);
long pivot = theArray[right];
// rightmost item
// partition range
int partition = partitionIt(left, right, pivot);
recQuickSort(left, partition-1); // sort left side
recQuickSort(partition+1, right); // sort right side
}
} // end recQuickSort()
//-------------------------------------------------------------public int partitionIt(int left, int right, long pivot)
{
int leftPtr = left-1;
// left (after ++)
int rightPtr = right;
// right-1 (after --)
while(true)
{
// find bigger item
while( theArray[++leftPtr] < pivot )
; // (nop)
// find smaller item
while(rightPtr > 0 && theArray[--rightPtr] > pivot)
; // (nop)
if(leftPtr >= rightPtr)
// if pointers cross,
break;
// partition done
else
// not crossed, so
swap(leftPtr, rightPtr); // swap elements
} // end while(true)
swap(leftPtr, right);
// restore pivot
return leftPtr;
// return pivot location
} // end partitionIt()
//-------------------------------------------------------------public void swap(int dex1, int dex2) // swap two elements
{
long temp = theArray[dex1];
// A into temp
theArray[dex1] = theArray[dex2]; // B into A
theArray[dex2] = temp;
// temp into B
} // end swap(
//-------------------------------------------------------------} // end class ArrayIns
public class randomizedQuickSort

{
public static void main(String[] args)
{
int maxSize = 16;
// array size
ArrayIns arr;
arr = new ArrayIns(maxSize); // create array
for(int j=0; j<maxSize; j++) // fill array with
{
// random numbers
long n = (int)(java.lang.Math.random()*99);
arr.insert(n);
}
arr.display();
// display items
arr.quickSort();
// quicksort them
arr.display();
// display them again
} // end main()
} // end class randomizedQuickSort

OUTPUT:
C:\>set path=C:\Program Files\Java\jdk1.6.0_02\bin
C:\Users\sen\Documents>javac randomizedQuickSort.java
C:\Users\sen\Documents>java randomizedQuickSort
A=63 60 38 12 66 67 31 59 73 28 29 32 95 80 19 70
A=12 19 28 29 31 32 38 59 60 63 66 67 70 73 80 95

RESULT:
Thus the source code was developed and executed successfully.

Ex No:6

IMPLEMENTATION OF VARIOUS LOCKING & SYNCHRONIZATION


Mechanisms For Concurrent Linked Lists, Concurrent Queues &
Concurrent Stacks

AIM:
To write a program to implement Concurrent Queues.
ALGORITHIM:
1. Start the program
2. Form a queue using four elements.
3. Process the following steps concurrently
(a) Trace the elements
(b) Check whether queue is empty
(c) Seek the element
(d) Remove the particular element
(e) Find the size of the program
PROGRAM:
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Stack;
class ConcurrentAccess{
synchronized public void list(LinkedList<Integer> list,int val)
{
list.add(val);
System.out.println(Thread.currentThread().getName()+": -------" + list);
}

synchronized public void queue(PriorityQueue<Integer> queue,int val)


{
queue.add(val);
System.out.println(Thread.currentThread().getName()+":------- " + queue);
}
synchronized public void stack(Stack<Integer> stack,int val)
{
stack.push(val);
System.out.println(Thread.currentThread().getName()+":-------- " + stack);
}
}
class AccessingList extends Thread
{
ConcurrentAccess concurrentAccess;
LinkedList<Integer> linkedList;
Thread thread;
int val;
AccessingList(ConcurrentAccess concurrentAccess,LinkedList<Integer>
linkedList,String threadName,int val)
{
this.concurrentAccess=concurrentAccess;
this.linkedList=linkedList;
this.val=val;
thread=new Thread(this,threadName);
thread.start();
}
@Override
public void run()
{
concurrentAccess.list(linkedList, val);
}
}
class AccessingQueue extends Thread
{
ConcurrentAccess concurrentAccess;
PriorityQueue<Integer> queue;
Thread thread;
int val;
AccessingQueue(ConcurrentAccess concurrentAccess,PriorityQueue<Integer>
queue,String threadName,int val)
{
this.concurrentAccess=concurrentAccess;
this.queue=queue;
this.val=val;
thread=new Thread(this,threadName);

thread.start();
}
@Override
public void run()
{
concurrentAccess.queue(queue, val);
}
}
class AccessingStack extends Thread
{
ConcurrentAccess concurrentAccess;
Stack<Integer> stack;
Thread thread;
int val;
AccessingStack(ConcurrentAccess concurrentAccess,Stack<Integer> stack,String
threadName,int val)
{
this.concurrentAccess=concurrentAccess;
this.stack=stack;
this.val=val;
thread=new Thread(this,threadName);
thread.start();
}
@Override
@SuppressWarnings("unchecked")
public void run()
{
concurrentAccess.stack(stack, val);
}
}
public class Student {
public static void main(String args[])
{
ConcurrentAccess concurrent=new ConcurrentAccess();
LinkedList<Integer> linkedList=new LinkedList<Integer>();
PriorityQueue<Integer> priorityQueue=new PriorityQueue<Integer>();
Stack<Integer> stack=new Stack<Integer>();
AccessingList accessingList=new AccessingList(concurrent, linkedList,"List Thread",
11);
AccessingQueue accessingQueue=new AccessingQueue(concurrent, priorityQueue,
"Queue Thread", 12);
AccessingStack accessingStack=new AccessingStack(concurrent, stack, "Stack
Thread", 13);

}
}
Output :
E:\abinaya\data structures lab>javac Student.java
E:\abinaya\data structures lab>java Student
List Thread: -------[11]
Stack Thread:-------- [13]
Queue Thread:------- [12]

RESULT:
Thus the source code was developed and executed successfully.

Ex No:7

DEVELOPING APPLICATIONS INVOLVING CONCURRENCY.

AIM:
To write a program to implement applications involving concurrency.
ALGORITHIM:
1. Start the program
2. Declare the sin,tan,cos values
3. Convert the degree into radius using the run() function
4. All the run functions executes concurrently
5. By using exceptions handling display the result
6. Stop the program
PROGRAM:
/* MathThreads.java: A program with multiple threads performing concurrent operations. */
import java.lang.Math;
class MathSin extends Thread {
public double deg;
public double res;
public MathSin(int degree) {
deg = degree;
}
public void run() {
System.out.println(Executing sin of +deg);
double Deg2Rad = Math.toRadians(deg);
res = Math.sin(Deg2Rad);
System.out.println(Exit from MathSin. Res = +res);
}
}
class MathCos extends Thread {
public double deg;
public double res;
public MathCos(int degree) {
deg = degree;
}
public void run() {
System.out.println(Executing cos of +deg);
double Deg2Rad = Math.toRadians(deg);
res = Math.cos(Deg2Rad);
System.out.println(Exit from MathCos. Res = +res);
}
}
class MathTan extends Thread {
public double deg;
public double res;

public MathTan(int degree) {


deg = degree;
}
public void run() {
System.out.println(Executing tan of +deg);
double Deg2Rad = Math.toRadians(deg);
res = Math.tan(Deg2Rad);
System.out.println(Exit from MathTan. Res = +res);
}
}
class MathThreads {
public static void main(String args[]) {
MathSin st = new MathSin(45);
MathCos ct = new MathCos(60);
MathTan tt = new MathTan(30);
st.start();
ct.start();
tt.start();
try { // wait for completion of all thread and then sum
st.join();
ct.join(); //wait for completion of MathCos object
tt.join();
double z = st.res + ct.res + tt.res;
System.out.println(Sum of sin, cos, tan = +z);
}
catch(InterruptedException IntExp) {
}
}
}
OUTPUT:
Run 1:
[raj@mundroo] threads [1:111] java MathThreads
Executing sin of 45.0
Executing cos of 60.0
Executing tan of 30.0
Multithreaded Programming
Exit from MathSin. Res = 0.7071067811865475
Exit from MathCos. Res = 0.5000000000000001
Exit from MathTan. Res = 0.5773502691896257
Sum of sin, cos, tan = 1.7844570503761732

Run 2:
[raj@mundroo] threads [1:111] java MathThreads
Executing sin of 45.0
Executing tan of 30.0
Executing cos of 60.0
Exit from MathCos. Res = 0.5000000000000001
Exit from MathTan. Res = 0.5773502691896257
Exit from MathSin. Res = 0.7071067811865475
Sum of sin, cos, tan = 1.7844570503761732
Run 3:
[raj@mundroo] threads [1:111] java MathThreads
Executing cos of 60.0
Executing sin of 45.0
Executing tan of 30.0
Exit from MathCos. Res = 0.5000000000000001
Exit from MathTan. Res = 0.5773502691896257
Exit from MathSin. Res = 0.7071067811865475
Sum of sin, cos, tan = 1.7844570503761732

RESULT:
Thus the source code was developed and executed successfully.

You might also like