CP7111-Advanced Data Structures Laboratory Manual
CP7111-Advanced Data Structures Laboratory Manual
CP7111-Advanced Data Structures Laboratory Manual
DIJKSTRAS ALGORITHM
AIM:
Given a graph with appropriate weights for each node, find the single source shortest path using Dijkstras algorithm.
ALGORITHM:
algorithm DijkstraShortestWeightedPath(G, s) _ pre-cond_: G is a weighted (directed or undirected) graph, and s is one of its nodes. _ post-cond_: specifies a shortest weighted path from s to each node of G, and d specifies their lengths. begin d(s) = 0, (s) = _ for other v, d(v)=and (v) = nil handled = notHandled = priority queue containing all nodes. Priorities given by d(v). loop _loop-invariant_: See above. exit when notHandled = let u be a node fromnotHandled with smallest d(u) for each v connected to u foundPathLength = d(u) +w_u,v_ if d(v) > foundPathLength then d(v) = foundPathLength (v) = u (update the notHandled priority queue) end if end for move u from notHandled to handled end loop return _d, _ end algorithm
SOURCE CODE:
package dijkstrashortestpath; import java.util.InputMismatchException; import java.util.Scanner; public class DijkstraShortestPath { private boolean settled[]; private boolean unsettled[]; private int distances[]; private int adjacencymatrix[][]; private int numberofvertices; public DijkstraShortestPath(int numberofvertices) { this.numberofvertices = numberofvertices; this.settled = new boolean[numberofvertices + 1]; this.unsettled = new boolean[numberofvertices + 1]; this.distances = new int[numberofvertices + 1]; this.adjacencymatrix = new int[numberofvertices + 1][numberofvertices + 1]; } public void dijkstraShortestPath(int source, int adjacencymatrix[][]) { int evaluationnode; for (int vertex = 1; vertex <= numberofvertices; vertex++) { distances[vertex] = Integer.MAX_VALUE; } for (int sourcevertex = 1; sourcevertex <= numberofvertices; sourcevertex++) { for (int destinationvertex = 1; destinationvertex <= numberofvertices; destinationvertex++) { this.adjacencymatrix[sourcevertex][destinationvertex] = adjacencymatrix[sourcevertex][destinationvertex]; } } unsettled[source] = true; distances[source] = 0; while (getUnsettledCount(unsettled) != 0) { evaluationnode = getNodeWithMinimumDistanceFromUnsettled(unsettled); unsettled[evaluationnode] = false; settled[evaluationnode] = true; evaluateNeighbours(evaluationnode);
} } public int getUnsettledCount(boolean unsettled[]) { int count = 0; for (int vertex = 1; vertex <= numberofvertices; vertex++) { if (unsettled[vertex] == true) { count++; } } return count; } public int getNodeWithMinimumDistanceFromUnsettled(boolean unsettled[]) { int min = Integer.MAX_VALUE; int node = 0; for (int vertex = 1; vertex <= numberofvertices; vertex++) { if (unsettled[vertex] == true && distances[vertex] < min) { node = vertex; min = distances[vertex]; } } return node; } public void evaluateNeighbours(int evaluationNode) { int edgeDistance = -1; int newDistance = -1; for (int destinationNode = 1; destinationNode <= numberofvertices; destinationNode++) { if (settled[destinationNode] == false) { if (adjacencymatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE) { edgeDistance = adjacencymatrix[evaluationNode][destinationNode]; newDistance = distances[evaluationNode] + edgeDistance; if (newDistance < distances[destinationNode]) { distances[destinationNode] = newDistance; } unsettled[destinationNode] = true; }
} } } public static void main(String... arg) { int adjacency_matrix[][]; int number_of_vertices; int source = 0; Scanner scan = new Scanner(System.in); 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]; System.out.println("Enter the Weighted Matrix for the graph"); for (int i = 1; i <= number_of_vertices; i++) { for (int j = 1; j <= number_of_vertices; j++) { adjacency_matrix[i][j] = scan.nextInt(); if (i == j) { adjacency_matrix[i][j] = 0; continue; } if (adjacency_matrix[i][j] == 0) { adjacency_matrix[i][j] = Integer.MAX_VALUE; } } } System.out.println("Enter the source "); source = scan.nextInt(); DijkstraShortestPath dijkstrasAlgorithm = new DijkstraShortestPath(number_of_vertices); dijkstrasAlgorithm.dijkstraShortestPath(source, adjacency_matrix); System.out.println("The Shorted Path to all nodes are "); for (int i = 1; i <= dijkstrasAlgorithm.distances.length - 1; i++) { System.out.println(source + " to " + i + " is "+ dijkstrasAlgorithm.distances[i]); } } catch (InputMismatchException inputMismatch) { System.out.println("Wrong Input Format"); }
scan.close(); } }
OUTPUT:
RESULT:
For the given nodes and the weights, the program successfully computed the shortest path from the source node to all other nodes in the given graph.
MAZE PROBLEM
ALGORITHM:
procedure PATH (MAZE, MARK, m, n, MOVE, STACK) MARK (1,1) 1 (STACK(1,1),STACK(1,2),STACK(1,3)) (1,1,2);top 1 while top 0 do (i,j,mov) (STACK(top,1),STACK(top,2), STACK(top,3) + 1) top top - 1 while mov 8 do g i + MOVE (mov,1); h j + MOVE(mov,2) if g = m and h = n then [for p 1 to top do //goal// print (STACK(p,1),STACK(p,2) end print(i,j); print(m,n);return] if MAZE(g,h) = 0 and MARK(g,h) = 0 then[MARK(g,h) 1 top top + 1 (STACK(top,1),STACK(top,2),STACK(top,3)) (i,j,mov) //save (i,j) as part of current path// mov 0; i g; j h] mov mov + 1 //point to next direction// end end print ('no path has been found) end path
SOURCE CODE: import java.awt.Point; public class MazeSolver { public static final char WALL_CHAR = '#'; public static final char FREE_CHAR = ' '; public static final char PATH_CHAR = '-'; public static final char START_CHAR = 'S'; public static final char FINISH_CHAR = 'F'; public MazeSolver ( char[][] newMaze ) { maze = newMaze; totalSteps = 0; startLocation = getStartLocation(); finishLocation = getFinishLocation(); } public void solve() { totalSteps = 0; if ( findPath(startLocation) ) { System.out.println("Solved the maze in " + totalSteps + " steps."); } else { System.out.println("Could not solve the maze!"); } } private boolean findPath( Point location ) { // If we're at the finish square, print the path if ( mazeFinished(location) ) { printMaze(); return true; } Point[] adjacentSquares = getAdjacentSquares(location); for ( Point potentialMove : adjacentSquares ) { if ( squareIsFree(potentialMove) ) { enterSquare(potentialMove); if ( findPath(potentialMove) ) { return true; } exitSquare(potentialMove); } }
return false; } private Point[] getAdjacentSquares ( Point location ) { Point[] adjacentSquares = new Point[4]; adjacentSquares[0] = new Point(location.x + 1, location.y); adjacentSquares[1] = new Point(location.x, location.y + 1); adjacentSquares[2] = new Point(location.x - 1, location.y); adjacentSquares[3] = new Point(location.x, location.y - 1); return adjacentSquares; } private boolean squareIsFree ( Point square ) { if ( square.x < 0 || square.x >= maze.length || square.y < 0 || square.y >= maze[square.x].length ) { return false; } return ( maze[square.x][square.y] == FREE_CHAR || maze[square.x][square.y] == FINISH_CHAR ); } private void enterSquare ( Point square ) { maze[square.x][square.y] = PATH_CHAR; totalSteps++; } private void exitSquare ( Point square ) { maze[square.x][square.y] = FREE_CHAR; totalSteps--; } private boolean mazeFinished ( Point location ) { return location.equals(finishLocation); } public void printMaze() { for ( int i = 0; i < maze.length; i++ ) { for ( int j = 0; j < maze[i].length; j++ ) { System.out.print(maze[i][j]); } System.out.println(); } System.out.println(); }
private Point getStartLocation() { Point startLocation = findChar(START_CHAR); if ( startLocation == null ) { throw new IllegalStateException("Maze has no start square!"); } return startLocation; } private Point getFinishLocation() { Point finishLocation = findChar(FINISH_CHAR); if ( finishLocation == null ) { throw new IllegalStateException("Maze has no finish square!"); } return finishLocation; }
private Point findChar( char c ) { for ( int i = 0; i < maze.length; i++ ) { for ( int j = 0; j < maze[i].length; j++ ) { if ( maze[i][j] == c ) { return new Point(i, j); } } } return null; } public static void main ( String[] args ) { char[][] easyMaze = { { WALL_CHAR, START_CHAR, WALL_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR }, { WALL_CHAR, FREE_CHAR, WALL_CHAR, WALL_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, WALL_CHAR }, { WALL_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR }, { WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR }, { WALL_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR },
{ WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, WALL_CHAR }, { WALL_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, FREE_CHAR, FREE_CHAR, WALL_CHAR, FREE_CHAR, FINISH_CHAR }, { WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR, WALL_CHAR } }; MazeSolver s = new MazeSolver(easyMaze); System.out.println("The maze looks like:"); s.printMaze(); s.solve(); } } OUTPUT:
RESULT: For a given maze of size 12*12, the program successfully computed the path from source the destination
ALGORITHM:
Given G=(V,E): Compute Degree(v) for all v in V. Set uncolored = V sorted in decreasing order of Degree(v). set currentColor = 0. while there are uncolored nodes: set A=first element of uncolored remove A from uncolored set Color(A) = currentColor set coloredWithCurrent = {A} for each v in uncolored: if v is not adjacent to anything in coloredWithCurrent: set Color(v)=currentColor. add v to currentColor. remove v from uncolored. end if end for currentColor = currentColor + 1. end while
SOURCE CODE:
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:
RESULT:
For given four vertices, the program successfully executed the graph coloring
ALGORITHM:
Input: Values (stored in array v) Weights (stored in array w) Number of distinct items (n) Knapsack capacity (W) for w from 0 to W do m[0, w] := 0 end for for i from 1 to n do for j from 0 to W do if j >= w[i] then m[i, j] := max(m[i-1, j], m[i-1, j-w[i]] + v[i]) else m[i, j] := m[i-1, j] end if end for end for
SOURCE CODE
import java.util.*; import java.io.*; import java.lang.*; public class Knapsack { static int n = 5, W; static obj st[]; public static BufferedReader br=new BufferedReader(new InputStreamReader( System.in ) ); 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]; for ( i = 0; i < n; i++ )
{ st[i] = new obj(); System.out.print ( "For Object " + ( i + 1 ) + " :-\n\tWeight: " ); st[i].weight = Float.parseFloat ( br.readLine() ); System.out.print ( "\tProfit: " ); st[i].profit = Float.parseFloat ( br.readLine() ); st[i].p_perKg = Round ( st[i].profit / st[i].weight, 2 ); System.out.print ( "\tProfit per Kg: " + st[i].p_perKg + "\n" ); st[i].index = i + 1; } bubbleSort(); System.out.print ( "\nOptimal Solution is : " ); fill_sack(); } public static float Round ( float Rval, int Rpl ) { float p = ( float ) Math.pow ( 10, Rpl ); Rval = Rval * p; float tmp = Math.round ( Rval ); return ( float ) tmp / p; } static void fill_sack() { float x[] = new float[n]; float u, tot_profit = 0; int i; for ( i = 0; i < n; i++ ) x[i] = 0; u = W; for ( i = 0; i < n; i++ ) { if ( st[i].weight > u ) break; x[i] = 1; u -= st[i].weight; System.out.print ( "\nAdded object " + st[i].index + " (" + st[i].profit + "Rs., " + st[i].weight + "Kg) completly in the bag.\n" ); System.out.print ( "Bag can still hold : " + u + "Kg" ); tot_profit += st[i].profit; } if ( i < n ) { x[i] = Round ( u / st[i].weight, 2 ); u -= Round ( st[i].weight * x[i], 2 ); System.out.print ( "\nAdded " + x[i] + " of object " + st[i].index + " (" + Round ( st[i].profit * x[i], 2 ) + "Rs., " + Round ( st[i].weight * x[i], 2 ) + "Kg) in the bag.\n" ); System.out.print ( "Bag can still hold : " + u + "Kg" ); tot_profit += Round ( st[i].profit * x[i], 2 ); } System.out.print ( "\n\nTotal Profit earned = Rs." + tot_profit + "/-" );
} static void bubbleSort() { for ( int pass = 1; pass < n; pass++ ) for ( int i = 0; i < n - pass; i++ ) if ( st[i].p_perKg < st[i+1].p_perKg ) { obj temp = new obj(); temp = st[i]; st[i] = st[i+1]; st[i+1] = temp; } } static class obj { float weight; float profit; float p_perKg; int index; } }
OUTPUT:
RESULT:
For given 3 objects, the program successfully computed total profit earned.
MINHEAP
AIM:
Given a heap, to find MINHEAP using java.
ALGORITHM:
Step 1: Start the program. Step 2 : Create a class NODE, containing an element and two self referential pointer LEFT_CHILD and RIGHT_CHILD. Step 3 : Create a class PQUEUE, containing an ROOT of class NODE and also define the ADT operations to be performed on Priority Queue. Step 4 : To INSERT an element into the tree, place the element and maintain the interior node should be minimum swap the nodes. Step 5 : To DELETE an element, swap the root node and maximum element in the tree, then delete the element. After deletion, the tree should be Minimum heap tree. Step 6 : To DISPLAY, contents of Priority Queue, use INORDER traversal by using recursion function then display the elements. Step 7 : Stop the program.
SOURCE CODE:
import java.io.*; public class minheap { private int[ ] heap; private int maxsize; private int size; public minheap(int max) { maxsize=max; heap=new int[maxsize]; size=0; heap[0]=Integer.MIN_VALUE; } private boolean isleaf(int pos) { return((pos>size/2)&&(pos<=size)); } private int leftchild(int pos) { if(!isleaf(pos)) return 2*pos; else return 0; } private int rightchild(int pos) { return 2*pos+1; } private int parent(int pos) { return pos/2; } private void swap(int pos1,int pos2) { int temp; temp=heap[pos1]; heap[pos1]=heap[pos2]; heap[pos2]=temp; } public void insert(int elm) { size++; heap[size]=elm; int current=size; while(heap[current]<heap[parent(current)]) { swap(current,parent(current));
current=parent(current); } } public void print() { int i; for(i=1;i<=size;i++) System.out.print(heap[i]+" "); System.out.println(); } public int removemin() { swap(1,size); size--; if(size!=0) pushdown(1); return heap[size+1]; } private void pushdown(int pos) { int smallchild; while(!isleaf(pos)) { smallchild=leftchild(pos); if((smallchild<size)&&(heap[smallchild]>heap[smallchild+1])) smallchild=smallchild+1; if(heap[pos]<=heap[smallchild])return; swap(pos,smallchild); pos=smallchild; } } public static void main(String args[]) { minheap o=new minheap(10); o.insert(50); o.insert(150); o.insert(5); o.insert(55); o.insert(25); o.insert(15); System.out.print("Heap is\n"); o.print(); int i=o.leftchild(1); System.out.print("\nLeft child is"+i+"\n"); i=o.leftchild(2); System.out.print("Left child is"+i+"\n"); i=o.leftchild(4); System.out.print("Left child is"+i+"\n"); o.removemin();
OUTPUT:
RESULT:
For given heap values, the program successfully executed the MINHEAP.
LEFTIST HEAP
AIM:
Given a heap, to implement Leftist Heap using java.
ALGORITHM:
Step1 : The standard heap functions make_heap(x) Creates and returns a leftist heap with a single element x insert(h,x) Inserts element x into heap h min(h) Returns the smallest element currently in the heap h remove_min(h) Similarly to the above returns the smallest element in the heap h,but also removes it from the heap make_heap(s) Creates and returns a leftist heap containing all elements in set s Step2 : Additional heap function merge(h1,h2) Merges leftist heaps h1 and h2 in to a single leftist heap. merge(Q) Merges leftist heaps in a non-empty queue Q. Step3 : lazy leftist heap functions lazy_merge(hi,h2) Merges leftist heaps h1 and h2 in to a single leftist heap. lazy_delete(h,p)
Marks element which is pointed at by pointer p as deleted. lazy_remove_min(h) Just like the remove_min above,but works even if there a dummy node lazy_min(h) Just like min above,but works even if there are dummy nodes in heap
SOURCE CODE:
import java.nio.BufferUnderflowException; public class LeftistHeap<AnyType extends Comparable<? super AnyType>> { public LeftistHeap( ) { root = null; } public void merge( LeftistHeap<AnyType> rhs ) { if( this == rhs ) // Avoid aliasing problems return; root = merge( root, rhs.root ); rhs.root = null; } private LeftistNode<AnyType> merge( LeftistNode<AnyType> h1, LeftistNode<AnyType> h2 ) { if( h1 == null ) return h2; if( h2 == null ) return h1; if( h1.element.compareTo( h2.element ) < 0 ) return merge1( h1, h2 ); else return merge1( h2, h1 ); } private LeftistNode<AnyType> merge1( LeftistNode<AnyType> h1, LeftistNode<AnyType> h2 ) { if( h1.left == null ) // Single node
h1.left = h2; // Other fields in h1 already accurate else { h1.right = merge( h1.right, h2 ); if( h1.left.npl < h1.right.npl ) swapChildren( h1 ); h1.npl = h1.right.npl + 1; } return h1; } private static <AnyType> void swapChildren( LeftistNode<AnyType> t ) { LeftistNode<AnyType> tmp = t.left; t.left = t.right; t.right = tmp; } public void insert( AnyType x ) { root = merge( new LeftistNode<AnyType>( x ), root ); } public AnyType findMin( ) { if( isEmpty( ) ) throw new BufferUnderflowException( ); return root.element; } public AnyType deleteMin( ) { if( isEmpty( ) ) throw new BufferUnderflowException( ); AnyType minItem = root.element; root = merge( root.left, root.right ); return minItem; } public boolean isEmpty( ) { return root == null; } public void makeEmpty( ) { root = null; } private static class LeftistNode<AnyType> { // Constructors LeftistNode( AnyType theElement ) { this( theElement, null, null ); } LeftistNode( AnyType theElement, LeftistNode<AnyType> lt, LeftistNode<AnyType> rt )
{ element = theElement; left = lt; right = rt; npl = 0; } AnyType element; LeftistNode<AnyType> left; LeftistNode<AnyType> right; int npl; } private LeftistNode<AnyType> root; public static void main( String [ ] args ) { int numItems = 10; LeftistHeap<Integer> h = new LeftistHeap<Integer>( ); LeftistHeap<Integer> h1 = new LeftistHeap<Integer>( ); int i = 37; for( i = 37; i != 0; i = ( i + 37 ) % numItems ) if( i % 2 == 0 ) { h1.insert( i ); System.out.println("Inserting " +i+ " into h1.. "); } else { h.insert( i ); System.out.println("Inserting " +i+ " into h.. "); } h.merge( h1 ); for( i = 1; i < numItems; i++ ) if( h.deleteMin( ) != i ) System.out.println( "Oops! " + i ); } }
OUTPUT:
RESULT:
For a given input, the program successfully executed Leftist heap.
TRIES
AIM:
Given nodes and its values, to implement tries in java.
ALGORITHM:
algorithm insert(root : node, s : string, value : any): node = root i =0 n = length(s) while i < n: if node.child(s[i]) != nil: node = node.child(s[i]) i=i+1 else: break (* append new nodes, if necessary *) while i < n: node.child(s[i]) = new node node = node.child(s[i]) i=i+1 node.value = value
SOURCE CODE
class Node { char content; boolean marker; Node[] child; public Node() { marker=false; child = new Node[26]; } public Node(int i) { content = (char)(int)('a'+i); marker=false;
child=new Node[26]; } } class Trie { private Node root; public Trie() { root=new Node(); root.content=' '; } public void insert(String s) { Node current=root; if(s.length()==0) current.marker=true; for(int i=0;i<s.length();i++) { if(current.child[(int)(s.charAt(i)-'a')]!=null) { current=current.child[(int)(s.charAt(i)-'a')]; System.out.println("Inserted Character:" + current.content); } else { current.child[(int)(s.charAt(i)-'a')]= new Node((int)(s.charAt(i)-'a')); current=current.child[(int)(s.charAt(i)-'a')]; System.out.println("Inserted Character:" + current.content); } if(i==s.length()-1) current.marker=true; } System.out.println("Finished Inserting the Word :" + s +"\n"); } public boolean search(String s) { Node current=root; System.out.println("Searching for string:" + s); while(current!=null) { for(int i=0;i<s.length();i++) { if(current.child[(int)(s.charAt(i)-'a')]==null) { System.out.println("Cannot find string :"+s); return false; } else { current=current.child[(int)(s.charAt(i)-'a')];
System.out.println("Found Character:" + current.content); } } if(current.marker==true) { System.out.println("Found String:"+s); return true; } else { System.out.println("Cannot find string :"+s+"(onle present as a substring)"); return false; } } return false; } } public class TestTrie { public static void main(String args[]) { Trie T=new Trie(); T.insert("google"); T.insert("goblet"); T.insert("yahoo"); T.insert(""); T.search("google"); T.search("goblets"); T.search("go"); T.search("blah"); T.search(""); } }
OUTPUT:
RESULT:
For a given set of values, the program successfully executed tries.
RANDOM SORT
AIM:
ALGORITHM:
set counter=0; increase counter to 1 while(!isSorted(i) calculate the index value using int index1 = (int) (Math.random() * i.length), index2 = (int) (Math.random() * i.length); Swap the index value When the value is lesser swap the next element to before element
SOURCE CODE:
public class RandomSort { public RandomSort(int[] i) { int counter = 0; while (!isSorted(i)) { shuffle(i); counter++; } System.out.println("Solution found! (shuffled " + counter + " times)"); print(i); } private void print(int[] i) { for (int x : i) { System.out.print(x + ", "); } System.out.println(); } private void shuffle(int[] i) { for (int x = 0; x < i.length; ++x) { int index1 = (int) (Math.random() * i.length), index2 = (int) (Math.random() * i.length); int a = i[index1]; i[index1] = i[index2];
i[index2] = a; } } private boolean isSorted(int[] i) { for (int x = 0; x < i.length - 1; ++x) { if (i[x] > i[x + 1]) { return false; } } return true; } public static void main(String[] args) { int[] i = { 1, 5, 2, 8, 5, 2, 4, 2, 6, 7, 66 }; new RandomSort(i); } }
OUTPUT:
RESULT:
For a given eleven values, the program successfully sorted the values in ascending order using random sort.
8- QUEEN PROBLEM
AIM:
Given the eight queens puzzle problem of placing eight chess queens on an 88 chessboard so that no two queens attack each other.
ALGORITHM:
Algorithm NQueens ( k, n) //Prints all Solution to the n-queens problem { for i := 1 to n do { if Place (k, i) then { x[k] := i; if ( k = n) then write ( x [1 : n] else NQueens ( k+1, n); } } } Eight Queens Problem Algorithm Place (k, i) { for j := 1 to k-1 do if (( x[ j ] = // in the same column or (Abs( x [ j ] - i) =Abs ( j k ))) // or in the same diagonal then return false; return true; }
SOURCE CODE:
public class EightQueens { public static void main(String args[]) { int N = 8; int[][] board = new int[N][N]; solve(0, board, N); for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { if(board[i][j]==1) System.out.print("Q "); else System.out.print("* "); } System.out.println();
} } static boolean solve(int row, int[][] board, int N) { if(row>=N) return true; for(int position = 0; position < N; position++) { if(isValid(board, row, position, N)) { board[row][position] = 1; if(!solve(row+1, board, N)) { board[row][position] = 0; } else return true; } } return false; } static boolean isValid(int[][] board, int x, int y, int N) { int i, j; for(i = 0; i < x; i++) if(board[i][y]==1) return false; i = x - 1; j = y - 1; while((i>=0)&&(j>=0)) if(board[i--][j--]==1) return false; i = x - 1; j = y + 1; while((i>=0)&&(j<N)) if(board[i--][j++]==1) return false; return true; } }
OUTPUT:
RESULT:
For a given 8*8 chess board, the program successfully placed 8 queens using backtracking.
ALGORITHM:
<Pre-condition>: First to check whether stack is empty or not. <Post-condition>: found the counter value after increment. When stack is empty , values are added . Condition -> for (int i = 0; i < 300; i++) To increment the counter value by using getAndIncrement() Exit the program, while condition is exist.
SOURCE CODE:
import java.util.concurrent.*; public class Exercise { static int counter = 0; static synchronized int getAndIncrement() { return counter++; } static class Improper implements Runnable { @Override public void run() { for (int i = 0; i < 300; i++) { getAndIncrement(); } } }
public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(3); for (int i = 0; i < 300; i++) { executorService.submit(new Improper()); } executorService.shutdown();
System.out.println(counter); } }
OUTPUT:
RESULT:
For a given input, the program successfully executed concurrent stack
CONCURRENT QUEUE
AIM:
Given a program, to implement Concurrent Queue in java.
ALGORITHM:
<Pre-condition>: Elements A, B, C, D . <Post-condition>: To arrange the elements into the concurrent linked queue. E - the type of elements held in this collection Serializable, Iterable<E>, Collection<E>, Queue<E> Creates a ConcurrentLinkedQueue that is initially empty Creates a ConcurrentLinkedQueue initially containing the elements of the given collection, added in traversal order of the collection's iterator. in interface public E poll() Description copied from interface: queue Retrieves and removes the head of this queue, or returns null if this queue is empty. Specified by: poll in interface Queue<E> Returns: the head of this queue, or null if this queue is empty public E peek() Description copied from interface: Queue Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. Specified by: peek in interface Queue<E> Returns: the head of this queue, or null if this queue is empt public boolean isEmpty() Returns true if this queue contains no elements. Specified by: isEmpty in interface Collection<E>
Overrides: isEmpty in class AbstractCollection<E> Returns: true if this queue contains no elements
SOURCE CODE:
package concurrentlinkedqueue; import java.util.concurrent.ConcurrentLinkedQueue; public class ConcurrentLinkedQueueDemo { public static void main(String args[]){ ConcurrentLinkedQueue clq = new ConcurrentLinkedQueue(); clq.add("A"); clq.add("B"); clq.add("C"); clq.add("D"); System.out.println("Element of queue = "+clq); Object obj = clq.peek(); System.out.println("Head element of queue = "+obj); boolean bol =clq.isEmpty(); System.out.println("Queue is empty : "+bol); boolean bol1 =clq.contains("D"); System.out.println("Is element 'D' existed into queue ? "+bol1); Object obj1 = clq.poll(); System.out.println("Removed head element = "+obj1); int i = clq.size(); System.out.println("Size of queue = "+i); } }
OUTPUT:
RESULT:
Given a queue of four elements, the program successfully executed concurrent linked queue.
ALGORITHM:
<Pre-condition>: Threads(A, B, C),Interruptions. <Post-condition>:Added the item into the Linked list. enqueue(Q:pointer to queue t, value: data type) node = new node() # Allocate a new node from the free list node>value = value # Copy enqueued value into node node>next.ptr = NULL # Set next pointer of node to NULL loop #Keep trying until Enqueue is done tail = Q>Tail # Read Tail.ptr and Tail.count together next = tail.ptr>next # Read next ptr and count fields together if tail == Q>Tail # Are tail and next consistent? if next.ptr == NULL # Was Tail pointing to the last node? if CAS(&tail.ptr>next, next, <node, next.count+1>) # Try to link node at the end of the linked list break # Enqueue is done. Exit loop endif else #Tail was not pointing to the last node CAS(&Q>Tail, tail, <next.ptr, tail.count+1>) # Try to swing Tail to the next node
endif
SOURCE CODE:
import java.util.Collections; import java.util.LinkedList; import java.util.List; public class EarlyNotify extends Object { private List list; public EarlyNotify() { list = Collections.synchronizedList(new LinkedList()); } public String removeItem() throws InterruptedException { synchronized (list) { while (list.isEmpty()) { print("wait()"); list.wait(); print("done with wait()"); } String item = (String) list.remove(0); return item; } } public void addItem(String item) { print("entering"); synchronized (list) { list.add(item); print("added: '" + item + "'"); list.notifyAll(); print("notified"); } print("leaving"); } private static void print(String msg) { String name = Thread.currentThread().getName(); System.out.println(name + ": " + msg); } public static void main(String[] args) { final EarlyNotify enf = new EarlyNotify(); Runnable runA = new Runnable() {
public void run() { try { String item = enf.removeItem(); print("returned: '" + item + "'"); } catch (InterruptedException ix) { print("interrupted!"); } 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"); 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) { } } }
OUTPUT:
RESULT:
For a given input values, the program successfully executed concurrent linked list.
AIM:
To find out the Maximum flow and Minimum cut in a graph for any given number of nodes.
ALGORITHM:
<pre_condition>: Max-Flow-Min-Cut ( graph G = ( V, E ), source S, terminal T, capacity C ) <post_condition>: Moved to sink of the graph. f := 0 (flow 0 on all edges) opt := false WHILE not opt DO construct the residual graph Gf find a directed path P from S to T in Gf IF such an augmenting path P exists THEN update flow f along P ELSE set opt := true; and X := the set of vertices in Gf END-WHILE return f as the max flow, and ( X , V-X ) as the min-cut END
SOURCE CODE:
package networkflowprob; 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]; } } 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; } 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("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:
RESULT:
For a given four nodes and graph matrix, the program successfully executed maximum flow and minimum cut.
RANDOMIZED TREAPS
AIM:
Given a program, to implement Randomized Treaps using java.
ALGORITHM:
Inserting a new element x: Choose prio(x). Search for the position of x in the tree. Insert x as a leaf. Restore the heap property. while prio(parent(x)) > prio(x) do if x is left child then RotateRight(parent(x)) else RotateLeft(parent(x)); endif endwhile;
Deleting an element x: Find x in the tree. while x is not a leaf do U: = child with smaller priority; if u is left child then RotateRight(x)) else RotateLeft(x); endif; endwhile;
Delete x;
Search for element with key k v := root; while v nil do case key(v) = k : stop; element found (successful search) key(v) < k : v:= RightChild(v); key(v) > k : v:= LeftChild(v); endcase; endwhile; element not found (unsuccessful search) Running time: O(# elements on the search path)
SOURCE CODE:
import java.util.Scanner; import java.util.Random; class TreapNode { TreapNode left, right; int priority, element; private static Random randomObj = new Random( ); public TreapNode(int theElement) { this(theElement, null, null); } public TreapNode(int theElement, TreapNode lt, TreapNode rt) { element = theElement; left = lt; right = rt; priority = randomObj.nextInt( ); } } class TreapTree
{ private TreapNode root; private static TreapNode nullNode; static { nullNode = new TreapNode(0); nullNode.left = nullNode.right = nullNode; nullNode.priority = Integer.MAX_VALUE; } public TreapTree() { root = nullNode; } public boolean isEmpty() { return root == nullNode; } public void makeEmpty() { root = nullNode; } public void insert(int x) { root = insert(x, root); } private TreapNode insert(int x, TreapNode t) { if (t == nullNode) t = new TreapNode(x, nullNode, nullNode); else if (x < t.element) { t.left = insert( x, t.left ); if (t.left.priority < t.priority) t = rotateWithLeftChild( t ); } else if (x > t.element) { t.right = insert( x, t.right ); if (t.right.priority < t.priority) t = rotateWithRightChild( t ); } return t; } public void remove(int x) { if (isEmpty()) System.out.println("Tree Empty"); else if (search(x) == false) System.out.println("Sorry "+ x +" is not present"); else
{ root = remove( x, root ); System.out.println(x+ " deleted from the tree"); } } private TreapNode remove(int x, TreapNode t) { if( t != nullNode ) { if (x < t.element) t.left = remove( x, t.left ); else if (x > t.element) t.right = remove( x, t.right ); else { if (t.left.priority < t.right.priority) t = rotateWithLeftChild( t ); else t = rotateWithRightChild( t ); if (t != nullNode) t = remove( x, t ); else t.left = nullNode; } } return t; } private TreapNode rotateWithLeftChild( TreapNode k2 ) { TreapNode k1 = k2.left; k2.left = k1.right; k1.right = k2; return k1; } private TreapNode rotateWithRightChild( TreapNode k1 ) { TreapNode k2 = k1.right; k1.right = k2.left; k2.left = k1; return k2; } public int countNodes() { return countNodes(root); } private int countNodes(TreapNode r) { if (r == nullNode) return 0; else
{ int l = 1; l += countNodes(r.left); l += countNodes(r.right); return l; } } public boolean search(int val) { return search(root, val); } private boolean search(TreapNode r, int val) { boolean found = false; while ((r != nullNode) && !found) { int rval = r.element; if (val < rval) r = r.left; else if (val > rval) r = r.right; else { found = true; break; } found = search(r, val); } return found; } public void inorder() { inorder(root); } private void inorder(TreapNode r) { if (r != nullNode) { inorder(r.left); System.out.print(r.element +" "); inorder(r.right); } } public void preorder() { preorder(root); } private void preorder(TreapNode r) { if (r != nullNode)
{ System.out.print(r.element +" "); preorder(r.left); preorder(r.right); } } public void postorder() { postorder(root); } private void postorder(TreapNode r) { if (r != nullNode) { postorder(r.left); postorder(r.right); System.out.print(r.element +" "); } } } public class TreapTest { public static void main(String[] args) { Scanner scan = new Scanner(System.in); TreapTree trpt = new TreapTree(); System.out.println("TreapTree Tree Test\n"); char ch; do { System.out.println("\nTreapTree Operations\n"); System.out.println("1. insert "); System.out.println("2. delete"); System.out.println("3. search"); System.out.println("4. count nodes"); System.out.println("5. check empty"); System.out.println("6. clear"); int choice = scan.nextInt(); switch (choice) { case 1 : System.out.println("Enter integer element to insert"); trpt.insert( scan.nextInt() ); break; case 2 : System.out.println("Enter integer element to delete"); try { trpt.remove( scan.nextInt() ); }
catch (Exception e) { System.out.println(e.getMessage()+" not found "); } break; case 3 : System.out.println("Enter integer element to search"); System.out.println("Search result : "+ trpt.search( scan.nextInt() )); break; case 4 : System.out.println("Nodes = "+ trpt.countNodes()); break; case 5 : System.out.println("Empty status = "+ trpt.isEmpty()); break; case 6 : System.out.println("\nTree Cleared"); trpt.makeEmpty(); break; default : System.out.println("Wrong Entry \n "); break; } System.out.print("\nPost order : "); trpt.postorder(); System.out.print("\nPre order : "); trpt.preorder(); System.out.print("\nIn order : "); trpt.inorder(); System.out.println("\nDo you want to continue (Type y or n) \n"); ch = scan.next().charAt(0); } while (ch == 'Y'|| ch == 'y'); } }
OUTPUT:
RESULT:
For a given three input values, the program successfully executed Treap operations like insert, delete, search, count nodes, check empty.
AIM:
Given a program, to implement Hashing with O (1) search time.
ALGORITHM:
typedef unsigned char HashIndexType; static const HashIndexType M = 158; typedef unsigned short int HashIndexType; static const HashIndexType M = 40503; typedef unsigned long int HashIndexType; static const HashIndexType M = 2654435769; w=bitwidth(HashIndexType) size of table=2**n static const int S = w - n; HashIndexType hashValue = (HashIndexType)(M * key) >> S; typedef unsigned short int HashIndexType; HashIndexType hash(int key) { static const HashIndexType M = 40503; static const int S = 6; return (HashIndexType)(M * key) >> S; } unsigned char hash(char *str) { unsigned char h = 0; while (*str) h += *str++; return h; } unsigned char rand8[256]; unsigned char hash(char *str) { unsigned char h = 0; while (*str) h = rand8[h ^ *str++]; return h; } unsigned char rand8[256]; unsigned short int hash(char *str) { unsigned short int h; unsigned char h1 h2;
if (*str == 0) return 0; h1 = *str; h2 = *str + 1; str++; while (*str) { h1 = rand8[h1 ^ *str]; h2 = rand8[h2 ^ *str]; str++; } h = ((unsigned short int)h1 << 8)|(unsigned short int)h2; return h % HASH_TABLE_SIZE
SOURCE CODE:
import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Set; public class HashtableDemo { public static void main(String args[]) { Hashtable companies = new Hashtable(); companies.put("Google", "United States"); companies.put("Nokia", "Finland"); companies.put("Sony", "Japan"); companies.get("Google"); System.out.println("Does hashtable contains Google "+companies.containsKey("Google")); System.out.println("Does hashtable contains Japan as value: " + companies.containsValue("Japan")); Enumeration enumeration = companies.elements(); while (enumeration.hasMoreElements()) { System.out.println("hashtable values: " + enumeration.nextElement()); } System.out.println("Is companies hashtable empty: "+ companies.isEmpty()); System.out.println("Size of hashtable in Java: " + companies.size()); Set hashtableKeys = companies.keySet(); Enumeration hashtableKeysEnum = companies.keys(); Enumeration hashtableValuesEnum = companies.elements(); Collection hashtableValues = companies.values(); companies.clear(); } }
as
key:
OUTPUT:
RESULT:
For a given hash table with its value and key, the program successfully executed its operations.
ALGORITHM:
Creating of threads new ExampleThread("Thread 1 ").start(); new ExampleThread("Thread 2 ").start(); Reads and writes operations of volatile variables can not be reordered with each other respect to each other or with respect to nonvolatile variable accesses. getName().compareTo("Thread 1 ") == 0 getName().compareTo("Thread 12") == 0 returns the thread value.
SOURCE CODE:
public class VolatileExample { public static void main(String args[]) { new ExampleThread("Thread 1 ").start(); new ExampleThread("Thread 2 ").start(); } } class ExampleThread extends Thread { private volatile int testValue = 1; public ExampleThread(String str){ super(str); } public void run() { for (int i = 0; i < 3; i++) { try { System.out.println(getName() + " : "+i);
if (getName().compareTo("Thread 1 ") == 0) { testValue++; System.out.println( "Test Value T1: " + testValue); } if (getName().compareTo("Thread 2 ") == 0) { System.out.println( "Test Value T2: " + testValue); } Thread.sleep(1000); } catch (InterruptedException exception) { exception.printStackTrace(); } } } }
OUTPUT:
RESULT:
For a given input values, the program successfully executed volatile fields.
LAMPORT BAKERY
AIM:
Given a program to implement Lamport Bakery algorithm.
ALGORITHM:
shared variable Choosing: array[1::N] of 0::1 initially 0; Number: array[1::N] of 0::1 initially 0 process p: =_ 1 _ p _ N _= private variable q: 1::N while true do 0: Noncritical Section; " 1: Choosing[p] := 1; Doorway 2: Number [p] := 1+maxfNumber [1]; : : : ; Number [N]g; # 3: Choosing[p] := 0; " 4: for q := 1 to N skip p do 5: await Choosing[q] = 0; =_ busy wait _= Bakery 6: await Number [q] = 0 _ (Number [p]; p) < (Number [q]; q) =_ busy wait _= od; # 7: Critical Section; 8: Number [p] := 0 Od shared variable
B: array[1::N] of boolean initially false; X: 1::N; Y : 0::N initially 0 process p: =_ 1 _ p _ N _= private variable j: 1::N while true do 0: Noncritical Section; B[p] := true; X := p; if Y 6= 0 then B[p] := false; await Y = 0; =_ busy wait _= goto 1_; Y := p; if X 6= p then B[p] := false; 10: for j := 1 to N do await :B[j] =_ busy wait _= od; if Y 6= p then await Y = 0; =_ busy wait _= goto 1__; Critical Section; Y := 0; B[p] := false
SOURCE CODE:
import java.util.*; import java.util.Scanner; import javax.swing.*; import java.awt.*; import java.awt.geom.*; public class lamport{ int e[][]=new int[10][10]; int en[][]=new int[10][10]; int ev[]=new int[10]; int i,p,j,k; HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); int xpoints[] =new int[5]; int ypoints[] =new int[5]; class draw extends JFrame{ private final int ARR_SIZE = 4; void drawArrow(Graphics g1, int x1, int y1, int x2, int y2) { Graphics2D g = (Graphics2D) g1.create(); double dx = x2 - x1, dy = y2 - y1; double angle = Math.atan2(dy, dx); int len = (int) Math.sqrt(dx*dx + dy*dy); AffineTransform at = AffineTransform.getTranslateInstance(x1, y1); at.concatenate(AffineTransform.getRotateInstance(angle)); g.transform(at); // Draw horizontal arrow starting in (0, 0) g.drawLine(0, 0, len, 0); g.fillPolygon(new int[] {len, len-ARR_SIZE, len-ARR_SIZE, len}, new int[] {0, -ARR_SIZE, ARR_SIZE, 0}, 4); }
public void paintComponent(Graphics g) { for (int x = 15; x < 200; x += 16) drawArrow(g, x, x, x, 150); drawArrow(g, 30, 300, 300, 190); }
public void paint(Graphics g){ int h1,h11,h12; Graphics2D go=(Graphics2D)g; go.setPaint(Color.black); for(i=1;i<=p;i++) { go.drawLine(50,100*i,450,100*i); } for(i=1;i<=p;i++) { for(j=1;j<=ev[i];j++) { k=i*10+j; go.setPaint(Color.blue); go.fillOval(50*j,100*i-3,5,5); go.drawString("e"+i+j+"("+en[i][j]+")",50*j,100*i-5); h1=hm.get(k); if(h1!=0) { h11=h1/10; h12=h1%10; go.setPaint(Color.red); drawArrow(go,50*h12+2,100*h11,50*j+2,100*i); } } } } } public void calc(){ Scanner sc=new Scanner(System.in); System.out.println("Enter the number of process:"); p=sc.nextInt(); System.out.println("Enter the no of events per process:"); for(i=1;i<=p;i++) { ev[i]=sc.nextInt(); } System.out.println("Enter the relationship:"); for(i=1;i<=p;i++)
{ System.out.println("For process:"+i); for(j=1;j<=ev[i];j++) { System.out.println("For event:"+(j)); int input=sc.nextInt(); k=i*10+j; hm.put(k,input); if(j==1) en[i][j]=1; } } for(i=1;i<=p;i++) { for(j=2;j<=ev[i];j++) { k=i*10+j; if(hm.get(k)==0) { en[i][j]=en[i][j-1]+1; } else { int a=hm.get(k); int p1=a/10; int e1=a%10; if(en[p1][e1]>en[i][j-1]) en[i][j]=en[p1][e1]+1; else en[i][j]=en[i][j-1]+1; } } } for(i=1;i<=p;i++) { for(j=1;j<=ev[i];j++) { System.out.println(en[i][j]); } } JFrame jf=new draw(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(500,500); jf.setVisible(true); } public static void main(String[] args){ lamport lam=new lamport();
lam.calc(); } }
OUTPUT:
RESULT:
For a given input values, the program successfully executed Lamport Bakery algorithm.