Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Aim:
To write a java program for the implementation of graph search algorithm using the concept
Breadth First Search and Depth First Search.
Algorithm:
Step1: Start the program.
Step2: Enter the number of vertices and edges.
Step3: Give the edge information.
Step4: Push the root node in the Stack or Queue.
Step5: Loop until the Stack or queue is empty.
Step6: Remove the node from the stack or Queue.
Step7: Then find the path from source to destination.
Step8: Stop the program.
Source Code:
import java.io.*;
class Node
{
int data;
Node link;
}
class QueueBFS
{
Node front,rear;
QueueBFS()
{
front=rear=null;
}
void insert(int x)
{
Node newrec=new Node();
newrec.data=x;
newrec.link=null;
if(front==null)
{
front=newrec;
}
else
P a g e 1 | 54
P a g e 2 | 54
P a g e 3 | 54
}
}
P a g e 4 | 54
OUTPUT:
P a g e 5 | 54
RESULT:
Thus the java program for the implementation of graph search algorithm using the concept
Breadth First and Depth First search has been executed successfully.
P a g e 6 | 54
Ex.No:2
Prims Algorithm
Aim:
To write a java program for the implementation of graph search algorithm using the concept
Prims Algorithm.
Algorithm:
Step1: Start the program
Step2: Enter the number of vertices and edges .
Step3: Give the edge information.
Step4: Enter the weight for each edge.
Step5: Then calculate minimum cost.
Step6: Find the Minimum Spanning Tree.
Step7: Stop the program.
Source Code:
import java.io.*;
import java.util.*;
class Graph
{
int weight[][]=new int[20][20];
int visited[]=new int [20];
int d[]=new int[20];
int p[]=new int[20];
int v,e;
void creategraph()throws IOException
{
int i,j,a,b,w;
BufferedReader in=new BufferedReader( new InputStreamReader(System.in));
System.out.print("\nEnter number of vertices :");
v=Integer.parseInt(in.readLine());
System.out.print("\nEnter number of
Edges :"); e=Integer.parseInt(in.readLine());
for ( i=1;i<=v;i++)
for( j=1;j<=v;j++)
weight[i][j]=0;
for (i=1;i<=v;i++)
{
p[i]=visited[i]=0;
d[i]=32767;
}
P a g e 7 | 54
P a g e 9 | 54
OUTPUT:
RESULT:
Thus the java program for the implementation of graph search algorithm using the concept
prims algorithm has been executed successfully.
P a g e 10 | 54
Ex.No:3
Kruskals Algorithm
Aim:
To write a java program for the implementation of graph search algorithm using the concept
Kruskals Algorithm.
Algorithm:
Step1: Start the program.
Step2: Enter the number of nodes in the undirected weighted graph.
Step3: Give weight for each edge.
Step4: Find the minimum spanning tree, which node forms a cycle it is
removed. Step5: Then find the cost for spanning tree.
Step6: Stop the program.
Source Code:
import java.io.*;
import java.util.*;
class Graphs
{
int i,n;
int noe;
int graph_edge[][]=new int[100][4];
int tree[][]=new int [10][10];
int sets[][]=new int[100][10];
int top[]=new int[100];
int cost=0;
int getNumber()
{
String str;
int ne=0;
InputStreamReader input=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(input);
try
{
str=in.readLine();
ne=Integer.parseInt(str);
}
catch(Exception e)
{
System.out.println("I/O Error");
}
return ne;
P a g e 11 | 54
}
}
return -1;
}
}
class Kruskal1
{
public static void main(String args[])
{
Graphs obj=new Graphs();
obj.read_graph();
obj.sort_edges();
obj.algorithm();
}
}
P a g e 14 | 54
OUTPUT:
RESULT:
Thus the java program for the implementation of graph search algorithm using the concept
kruskals algorithm has been executed successfully.
P a g e 15 | 54
Aim:
To write a java program for the implementation of Network Flow by finding the maximum
flow and minimum cut of a network.
Algorithm:
Step1: Start the program.
Step2: Enter the number of nodes.
Step3: Determine the Graph matrix.
Step4: Enter the source and sink in the graph.
Step5: Find the Maximum flow and minimum Cut set in the graph.
Step6: Stop the program.
Source Code:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set; public
class NetworkFlowProb
{
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>();
P a g e 16 | 54
P a g e 19 | 54
OUTPUT:
RESULT:
Thus the java program for the implementation of Network Flow by finding the maximum
flow and minimum cut of a network has been successfully executed.
P a g e 20 | 54
Aim:
To write a java program for the Implementation of hill climbing using travelling salesman
problem.
Algorithm:
Step1: Start the program
Step2: Enter the number of nodes.
Step3: Specify the weight for each edge.
Step4: Assume the starting node.
Step5: Find the tour and its cost.
Step6: Stop the program.
Source Code:
import java.util.*;
import java.text.*;
class TSP
{
int weight[][],n,tour[],finalCost;
final int INF=1000;
public TSP()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no. of
nodes:=>"); n=s.nextInt();
weight=new int[n][n];
tour=new int[n-1];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
System.out.print("Enter weight of "+(i+1)+" to "+
(j+1)+":=>"); weight[i][j]=s.nextInt();
}}}
System.out.println();
System.out.println("Starting node assumed to be node
1."); eval();
P a g e 21 | 54
P a g e 23 | 54
OUTPUT:
RESULT:
Thus the java program for the implementation of Hill climbing algorithm using travelling
salesman problem has been executed successfully.
P a g e 24 | 54
Ex.No:6
Aim:
To write a java program for the Implementation of dynamic programming using longest
common subsequences problem.
Algorithm:
Step1: Start the program.
Step2: Enter the string1 and string2.
Step3: Determine the common sequence by matching the strings.
Step4: Find the length of longest common subsequence.
Step5: Display the common sequence between the given input strings.
Step6: Stop the program.
Source Code:
import java.util.*;
class lcs
{
static class cell
{
int cost, parent;
}
static final int MAXLEN = 100;
static cell m[][] = new cell[MAXLEN][MAXLEN];
static final int MATCH = 0;
static final int INSERT = 1;
static final int DELETE =
2; static int indel(char c)
{return 1;}
static int match(char c, char d)
{
if(c==d) return 0;
return MAXLEN;
}
static void row_init(int i)
{
m[0][i].cost = i;
if (i>0) m[0][i].parent = INSERT;
else m[0][i].parent = -1; }
static void column_init(int i)
{
m[i][0].cost = i;
P a g e 25 | 54
}
static int string_compare(String s, String t)
{
for(int i=0;i<MAXLEN;i++)
{
row_init(i);
column_init(i);
} int k,
lowest_cost;
int opt[] = new int [3];
for(int i=1;i<s.length();i++)
for(int j=1;j<t.length();j++)
{
opt[MATCH] = m[i-1][j-1].cost + match(s.charAt(i),t.charAt(j));
opt[INSERT] = m[i][j-1].cost + indel(t.charAt(j)); opt[DELETE] =
m[i-1][j].cost + indel(s.charAt(i));
m[i][j].cost = opt[MATCH];
m[i][j].parent = MATCH;
for (k=INSERT; k<=DELETE; k++)
if (opt[k] < m[i][j].cost)
{
m[i][j].cost = opt[k];
m[i][j].parent = k;
}}
return m[s.length()-1][t.length()-1].cost;
}
static void print_matrix(String s, String t, boolean costQ)
{
int x = s.length();
int y = t.length();
System.out.printf(" ");
for(int i=0;i<y;i++)
System.out.printf(" %c",t.charAt(i));
System.out.printf("\n");
for(int i=0; i<x; i++)
{ System.out.printf("%c:
",s.charAt(i)); for(int j=0; j<y; j++) {
if(costQ)
System.out.printf(" %2d",m[i][j].cost);
else
System.out.printf(" %2d",m[i][j].parent);
}
System.out.printf("\n");
}}static void reconstruct_path(String s, String t, int i, int j)
P a g e 26 | 54
P a g e 27 | 54
OUTPUT:
RESULT:
Thus the java program for the implementation of Dynamic Programming using longest
common subsequences problem has been executed successfully.
P a g e 28 | 54
N Queens Problem
Aim:
To write a java program for implementation of Recursive Backtracking Algorithms using N
Queens Problem.
Algorithm:
Step1: Start the program.
Step2: Enter the board size.
Step3: Then place the queen based on board size.
Step4: Find the solution for given board size.
Step5: Check the condition board size less than or equal to row and column the print
Q. Step6: Otherwise print dot(.).
Step7: Repeat Step5 until there is no solution possible.
Step8: Stop the program.
Source Code:
import java.util.Scanner;
public class Queens
{
protected int boardSize;
protected boolean[][] board;
public Queens (int boardSize)
{
this.boardSize = boardSize;
board = new boolean[boardSize][boardSize];
for (int row = 0; row < boardSize; row++)
for (int column = 0; column < boardSize; column+
+) board[row][column] = false;
}
protected boolean placeQueen (int column)
{
int row;
if (column == boardSize)
{
return true;
}
else
{
boolean successful =
false; row = 0;
P a g e 29 | 54
P a g e 31 | 54
OUTPUT:
RESULT:
Thus the java program for the implementation of recursive backtracking algorithm using
NQueens problem has been executed successfully.
P a g e 32 | 54
Ex.No:8
Permutations
Aim:
To write a java program for implementation of Recursive Backtracking Algorithms using
Permutation Problem.
Algorithm:
Step1: Start the program.
Step2: Enter the initial string.
Step3: Find the permutation for given string.
Step4: Check the condition for ending string which is less than or equal to value
1. Step5: Print the string.
Step6: Stop the program.
Source Code:
import java.io.*; public
class permutation
{
public static void main(String args[]) throws IOException
{
String str;
System.out.println("Enter the initial string");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
System.out.println("Permutations
are :"); permute("", str);
}
public static void permute(String beginningString, String endingString)
{
if (endingString.length() <= 1)
System.out.println(beginningString + endingString);
else
for (int i = 0; i < endingString.length(); i++)
{
try {
String newString = endingString.substring(0, i) + endingString.substring(i + 1);
permute(beginningString + endingString.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception)
{
exception.printStackTrace() } }}}
P a g e 33 | 54
OUTPUT:
RESULT:
Thus the java program for the implementation of recursive backtracking algorithm using
Permutation problem has been executed successfully.
P a g e 34 | 54
Quick Sort
Aim:
To write a java program for the implementation of Randomized Algorithms using Quick
Sort problem.
Algorithm:
Step1: Start the program.
Step2: Enter the limit for its elements.
Step3: Check if low is less than or equal to high then, temp=a[low];
a[low]=a[high]; a[high]=temp;
Step4: Then increment low and decrement high.
Step5: Display the sorted array elements in ascending order.
Step6: Stop the program.
Source Code:
import java.io.*; import
java.util.Scanner;
import java.util.Random;
public class quicksort{
private static final Random rnd =new Random();
public static void main(String[] args){
int i;
Scanner in=new Scanner(System.in);
System.out.println(" Quick Sort\n");
System.out.println("Enter the no. of elements in the
array:\n"); int arr_val=in.nextInt();
int array[]=new
int[arr_val]; try
{
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nEnter the Array Elements:\n");
for(i=0;i<arr_val;i++)
{
array[i]=Integer.parseInt(br.readLine());
}
}
catch(Exception ex)
{
}
P a g e 35 | 54
OUTPUT:
P a g e 36 | 54
RESULT:
Thus the java program for the implementation of randomized algorithm using quick sort
problem has been executed successfully.
P a g e 37 | 54
Matrix Multiplication
Ex.No:10
Aim:
To write a java program for the implementation of Randomized Algorithms using Matrix
Multiplication problem.
Algorithm:
Step1: Start the program.
Step2: Enter the matrix dimension.
Step3: Then create a matrices function.
Step4: Fill the first matrix with the random numbers.
Step5: Check the condition for the first matrix that number less than dimension.
Step6: Then fill the second matrix with the random numbers.
Step7: Check the condition for the second matrix that number less than dimension.
Step8: Multiplying the matrices.
Step9: Display the resulting matrix.
Step10: Stop the program.
Source Code:
import java.util.Scanner;
import java.util.Random;
}
}
P a g e 39 | 54
OUTPUT:
RESULT:
Thus the java program for the implementation of randomized algorithm using matrix
multiplication problem has been executed successfully.
P a g e 40 | 54
Aim:
To write a java program to implement the various locking and synchronization mechanisms for
Concurrent Linked List.
Algorithm:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: Define the Linked Node definition.
Step 4: Create a constructor to build a node with null and specified constructor.
Step 5: Create a linked list class.
Step 6: Check for assertion if the assertion is not true then it throws java.lang.assertion error.
Step 7: Create a function to check if the list is empty or not.
Step 8: Display the result.
Step 9: Stop the program.
Source Code:
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
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();
P a g e 43 | 54
OUTPUT :
RESULT :
Thus a java program to implement the various locking and synchronization mechanisms for
Concurrent Linked List has been executed successfully.
P a g e 44 | 54
Ex.No : 12
Concurrent Queue
Aim:
To write a java program to implement producer consumer problem using concurrent blocking
Queue.
Algorithm:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: Create the shared object for the class using blocking queue.
Step 4: Create producer class in java.
Step 5: Create consumer class in java.
Step 6: Display the result.
Step 7: Stop the program.
Source Code:
import java.io.*; import
java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProducerConsumerPattern
{
public static void main(String args[])
{
BlockingQueue sharedQueue = new LinkedBlockingQueue();
Thread prodThread = new Thread(new Producer(sharedQueue));
Thread consThread = new Thread(new Consumer(sharedQueue));
prodThread.start();
consThread.start();
}
}
class Producer implements Runnable
{
private final BlockingQueue sharedQueue;
public Producer(BlockingQueue sharedQueue)
{
this.sharedQueue = sharedQueue;
}
public void run()
{
for(int i=0; i<10; i++)
P a g e 45 | 54
}
catch (InterruptedException ex)
{
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
class Consumer implements Runnable
{
private final BlockingQueue sharedQueue;
Consumer (BlockingQueue sharedQueue)
{ this.sharedQueue = sharedQueue;
}
public void run()
{
while(true)
{
try
{
System.out.println("Consumed: "+ sharedQueue.take());
}
catch (InterruptedException ex)
{
Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
P a g e 46 | 54
OUTPUT :
RESULT :
Thus a java program to implement producer consumer problem using concurrent blocking Queue
has been successfully executed.
P a g e 47 | 54
Ex.No : 13
Concurrent Stack
Aim:
To write a java program to implement concurrent stack using push and pop.
Algorithm:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: Create a class stackimpl2
Step 4: Initialize the stack using push and pop.
Step 5: Create a wait() method that is called to pop the waiting element.
Step 6: Create a notify() method to notify the popped elements.
Step 7: Stackuser class has been created to extends thread.
Step 8: Start Daemon thread using set daemon.
Step 9: Start this thread.
Step10: Display the result.
Source Code:
Import java.io.*;
class StackImpl2
{
private Object[] stackArray;
private volatile int topOfStack;
StackImpl2 (int capacity)
{
stackArray = new
Object[capacity]; topOfStack = -1;
}
public synchronized Object pop()
{
System.out.println(Thread.currentThread() + ":
popping"); while (isEmpty())
try
{
System.out.println(Thread.currentThread() + ": waiting to
pop"); wait(); // (1)
}
catch (InterruptedException
e) { }
Object obj = stackArray[topOfStack];
stackArray[topOfStack--] = null;
System.out.println(Thread.currentThread() + ": notifying after pop");
P a g e 48 | 54
notify();
return obj;
// (2)
P a g e 49 | 54
}
public synchronized void push(Object element)
{
System.out.println(Thread.currentThread() + ": pushing");
while (isFull())
try
{
System.out.println(Thread.currentThread() + ": waiting to push");
wait(); // (3)
}
catch (InterruptedException e)
{}
stackArray[++topOfStack] = element;
System.out.println(Thread.currentThread() + ": notifying after push");
notify(); // (4)
} public boolean
isFull()
{
return topOfStack >= stackArray.length -1;
}
public boolean isEmpty()
{
return topOfStack < 0;
}
}
abstract class StackUser extends Thread
{ // (5) Stack user protected StackImpl2 stack; // (6)
StackUser(String threadName, StackImpl2 stack)
{
super(threadName);
this.stack = stack;
System.out.println(this);
setDaemon(true); start();
// (7) Daemon
thread // (8) Start this thread
}
}
class StackPopper extends StackUser
{ // (9) Popper
StackPopper(String threadName, StackImpl2 stack)
{
super(threadName, stack);
}
public void run()
P a g e 50 | 54
OUTPUT :
RESULT :
Thus to write a java program to implement concurrent stack using push and pop has been
executed successfully.
P a g e 51 | 54
Aim:
To write a java program to implement Sleeping Barber problem using Concurrency.
Algorithm:
Step 1: Import the header files.
Step 2: Declare the number of chairs and barbers in the
shop Step 3: Enter the number of customer.
Step 4: If there is no customer to be served, the barber goes to sleep.
Step 5:If a customer enters the barber shop whole chairs are occupied, then the customer
leaves the Shop.
Step 6: If the barber is busy, but chairs are available in waiting room then the customer sits
in one of the free chairs until the barber is idle.
Step 7: Barber class which extends threads is used to simulate multiple sleeping barbers
Source Code:
import java.io.*;
import java.lang.*;
class cust
{
public int disp(int cn)
{
return(cn);
}
}
class em1 extends
Thread{ Barber m=new
Barber(); cust c=new
cust();
public synchronized void run()
{
try
{
while(m.cnum<=m.n)
{
int t=c.disp(m.cnum++);
System.out.println("Barber2 serves Customer
"+t); Thread.sleep(2000);
}
P a g e 52 | 54
OUTPUT :
RESULT :
Thus a java program to implement Sleeping Barber problem using Concurrency has been
executed successfully.
P a g e 54 | 54