You are on page 1of 70

Ex:No: 1a

Date:

IMPLEMENTATION OF GRAPH SEARCH


ALGORITHMS
Breadth First Search (BFS)

AIM
To traverse the graph using Breadth First Search (BFS) algorithm.

ALGORITHM
Step 1 : Consider the given instance of a graph.
Step 2 : Begin the traversal from the root node S(Source node).
Step 3 : Visit all the neighbor nodes of S.
Step 4 : Traverse the graph from left to right.
Step 5 : Visit all the neighbors of each node.
Step 6 : If the node cant be traversed, consider that node as already visited.
Step 7 : Proceed the traversal again until all the nodes in the graph are visited.
Step 8 : Terminate the program

PROGRAM
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
{
rear.link=newrec;
}
rear=newrec;
}
int delete()
{
2

if(front!=null)
{
int temp;
temp=front.data;
front=front.link;
return temp;
}
else
{
System.out.println("Empty queuebfs");
return -1; } } }
class Graph
{
int g[][];
int v,e;
int visited[];
int a,b;
QueueBFS q=new QueueBFS();
void createGraph()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of vertices:");
v=Integer.parseInt(br.readLine());
System.out.println("Enter the number of edges:");
e=Integer.parseInt(br.readLine());
g=new int[v+1][v+1];

for(int i=1;i<=e;i++)
{
System.out.println("Enter the Edge information:");
System.out.println("From=");
3

a=Integer.parseInt(br.readLine());
System.out.println("To=");
b=Integer.parseInt(br.readLine());
g[a][b]=g[b][a]=1; } }
void callBfs()
{
visited=new int[v+1];
bfs(1);
}
void bfs(int k)
{
q.insert(k);
while(q.front!=null)
{
k=q.delete();
visited[k]=1;
System.out.print(k+"\t");
for(int i=1;i<=v;i++)
{
if(g[k][i]!=0 && visited[i]!=1)
{
q.insert(i);
visited[i]=1; } } } } }
class BFSMain
{
public static void main(String args[])throws IOException
{
Graph g=new Graph();
g.createGraph();
g.callBfs();
}}
4

OUTPUT

RESULT
Thus the program for graph search algorithm using Breadth First Search (BFS)
has been compiled and executed successfully.

Ex:No:1b
Date:

IMPLEMENTATION OF GRAPH SEARCH


ALGORITHMS
Depth First Search (DFS)

AIM
To traverse the graph using Depth First Search (DFS) algorithm.

ALGORITHM
Step 1 : Consider the given instance of a graph.
Step 2 : Begin the traversal from the root node (Source node S).
Step 3 : Visit all the successive nodes of S.
Step 4 : Traverse the graph from top to bottom of each branch.
Step 5 : Visit all the successors of each node.
Step 6 : If the node cant be traversed, consider that node as already visited.
Step 7 : Proceed the traversal again until all the nodes in the graph are visited.
Step 8 : Terminate the program

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");
7

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");
for (i=0; i<n; i++)
if (m[i]==0)
dfs(a,m,i,n); } }

OUTPUT

RESULT
Thus the program for graph search algorithm using Depth First Search(DFS)
has been compiled and executed successfully.
9

Ex:No:2a
Date:

IMPLEMENTATION OF NETWORK FLOW


PROBLEM

AIM:
To implement the concept of network flow problem.

PROCEDURE:
Step1: Start the program
Step2: Get the number nodes as input
Step3: Calculate the graph matrix
Step4: Compute source of the graph
Step5: Compute the sink of the graph
Step6: Calculate the maximum flow
Step7: Calculate the cut set
Step 8: End the program.

10

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[][])


11

{
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;
12

}
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])
13

{
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;
14

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();
}
15

}
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() { } }

16

OUTPUT:

RESULT:
Thus the implementation of network flow problem has been successfully compiled and
executed.

17

Ex:No:2b
Date:

IMPLEMENTATION OF LINEAR
PROGRAMMING N QUEEN'S PROBLEM

AIM:
To write a java program to implement the application of linear programming in NQueens problem.
ALGORITHM:
Step 1: Start the program.
Step 2: Define the needed packages in java.
Step 3: Create the class with specific name.
Step 4: Declare and initialize the array size.
Step 5: Set the loop conditions.
Step 6: Call the function callplacequeens().
Step 7: Try all the permutations using recursive backtracking.
Step 8: Place the queen in which no two queens are on the same row, same column and
on the major diagonal.
Step 9: Print the result.

18

PROGRAM:
import java.io.*;
public class Queens
{
int[] x;
public Queens(int N) {
x = new int[N];
}
public boolean canPlaceQueen(int r, int c)
{
for (int i = 0; i < r; i++)
{
if (x[i] == c || (Math.abs(i - r) == Math.abs(x[i] - c)) )
{
return false;
}
}
return true;
}
public void printQueens(int[] x) {
int N = x.length;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (x[i] == j) {
System.out.print("Q ");
}
else {
System.out.print("* ");
}
}
System.out.println();
}
System.out.println();
}
public void placequeens(int r, int n) {
for (int c = 0; c < n; c++) {
if (canPlaceQueen(r, c)) {
x[r] = c;
19

if (r == n - 1) {
printQueens(x);
}
else {
placequeens(r + 1, n);
}}
}}
public void callplacequeens()
{
placequeens(0, x.length);
}
public static void main(String args[]) {
Queens Q = new Queens(8);
Q.callplacequeens();
}
}

20

OUTPUT:

RESULT:
Thus the concept of linear programming was implemented by N Queens problem and the
output was verified successfully.

21

Ex:No:3a
Date:

IMPLEMENTATION OF ALGORITHM USING


HILLCLIMBING TECHNIQUE

AIM:
To write a java program for implementation of traveling salesman problem using hill
climbing.
ALGORITHM:
Step 1: Start the program with nodes as input in the form of the cost matrix.
Step 2: Cost of the given nodes is obtained from the sum of reductions as lower
bound on the tour.
Step 3: Node say x, is the destination node which is the city pair to be reached.
Step 4: To find the city pair x from source node say s, branch to a node k which
maximizes and extend the tree from s to x.
Step 5: Add Q(s,k) to the lower bound of X to set the lower bound of the new node.
Step 6: If the number of city pairs committed to the tours branches to node x, Finish
the branching otherwise go to step 4.
Step 7: Delete row and column in the cost matrix of nodes where tour is undone.
Step 8: Add the amount of the reduction to the lower bound of X to set the lower
bound for the new node.
Step 9: End the program.

22

PROGRAM:
import java.util.*;
import java.text.*;
class TSP
{
int weight[][],n,tour[],finalCost;
final int INF=1000;
public TSP()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no. of nodes:=>");
n=s.nextInt();
weight=new int[n][n];
tour=new int[n-1];
for(int i=0;i<n;i++)

{
for(int j=0;j<n;j++)
{
if(i!=j)
{
System.out.print("Enter weight of "+(i+1)+" to "+(j+1)+":=>");
weight[i][j]=s.nextInt();
}
}
}
System.out.println();
System.out.println("Starting node assumed to be node 1.");
eval();
}
public int COST(int currentNode,int inputSet[],int setSize)
23

{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
int setToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setSize;i++)
{
int k=0;//initialise new set
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
minindex=inputSet[i];
}
}
return min;
}
public int MIN(int currentNode,int inputSet[],int setSize)
{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
int setToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setSize;i++)//considers each node of inputSet
{
int k=0;
24

for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
minindex=inputSet[i];
}
}
return minindex;
}
public void eval()
{
int dummySet[]=new int[n-1];
for(int i=1;i<n;i++)
dummySet[i-1]=i;
finalCost=COST(0,dummySet,n-1);
constructTour();
}
public void constructTour()
{
int previousSet[]=new int[n-1];
int nextSet[]=new int[n-2]; for(int i=1;i<n;i++)
previousSet[i-1]=i;
int setSize=n-1;
tour[0]=MIN(0,previousSet,setSize);
for(int i=1;i<n-1;i++)
{
25

int k=0;
for(int j=0;j<setSize;j++)
{
if(tour[i-1]!=previousSet[j])
nextSet[k++]=previousSet[j];
}
--setSize;
tour[i]=MIN(tour[i-1],nextSet,setSize);
for(int j=0;j<setSize;j++)
previousSet[j]=nextSet[j];
}
display();
}
public void display()
{
System.out.println();
System.out.print("The tour is 1-");
for(int i=0;i<n-1;i++)
System.out.print((tour[i]+1)+"-");
System.out.print("1");
System.out.println();
System.out.println("The final cost is "+finalCost);
}
}
class TSPExp
{
public static void main(String args[])
{
TSP obj=new TSP();
}
}
26

OUTPUT:

RESULT:
Thus the traveling salesman problem using hill climbing was implemented and the
output was verified successfully.

27

Ex:No:3b
Date:

IMPLEMENTATION OF ALGORITHM USING


DYNAMIC PROGRAMMING TECHIQUE

AIM:
To write a java program for the implementation of knapsack problem using dynamic
programming.

ALGORITHM:
Step 1: Start the program.
Step 2: Given some items, pack the knapsack to obtain maximum profit.
Step 3: Each item has some weight and some profit.
Step 4: Total weight that an item can carry is no more than some fixed number W.
Step 5: Dynamic programming approach used can either accept an Item or remove the
item

since items are indivisible.

Step6: Inorder to achieve a knapsack with maximum total profit and total less weight
of

packed items,2n possible combinations of each item is gonethrough.

Step 7: Terminate the program once item with maximum profit is obtained.

28

PROGRAM:
public class Knapsack {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // number of items
int W = Integer.parseInt(args[1]); // maximum weight of knapsack

int[] profit = new int[N+1];


int[] weight = new int[N+1];

// generate random instance, items 1..N


for (int n = 1; n <= N; n++) {
profit[n] = (int) (Math.random() * 1000);
weight[n] = (int) (Math.random() * W);
}

// opt[n][w] = max profit of packing items 1..n with weight limit w


// sol[n][w] = does opt solution to pack items 1..n with weight limit w include item n?
int[][] opt = new int[N+1][W+1];
boolean[][] sol = new boolean[N+1][W+1];
for (int n = 1; n <= N; n++) {
for (int w = 1; w <= W; w++) {

// don't take item n


int option1 = opt[n-1][w]; // take item n
int option2 = Integer.MIN_VALUE;
if (weight[n] <= w) option2 = profit[n] + opt[n-1][w-weight[n]];
opt[n][w] = Math.max(option1, option2);
sol[n][w] = (option2 > option1);
}
29

}
boolean[] take = new boolean[N+1];
for (int n = N, w = W; n > 0; n--) {
if (sol[n][w]) {
take[n] = true; w = w - weight[n];
}
else

{ take[n] = false;

// print results
System.out.println("item" + "\t" + "profit" + "\t" + "weight" + "\t" + "take");
for (int n = 1; n <= N; n++) {
System.out.println(n + "\t" + profit[n] + "\t" + weight[n] + "\t" + take[n]);
}
}
}

30

OUTPUT:

RESULT:
Thus the knapsack problem using dynamic programming was implemented and the
output was verified successfully.

31

Ex:No:4a
Date:

IMPLEMENTATION OF RECURSIVE
BACKTRACKING ALGORITHMS

AIM
To implement recursive backtracking algorithms using maze generator.
ALGORITHM:
Step 1: start the program.
Step 2: Initialize the variables.
Step3: Search for a solution by constructing partial solutions that remain consistent with
the requirements of the problem.
step 4: extend a partial solution toward completion of the problem.
step 5: When inconsistency occurs, the algorithms backs up (backtracks) by
removing the most recently constructed part of the solution.
step 6: Try another possibility for the problem.
step 7: Stop the program.

32

PROGRAM
import java.util.*;
public class MazeGenerator {
private final int x;
private final int y;
private final int[][] maze;
private static final Random rand = new Random();
public MazeGenerator(int x, int y) {
this.x = x;
this.y = y;
maze = new int[this.x][this.y];
generateMaze(0, 0);
}
public void display() {
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
System.out.print((maze[j][i] & 1) == 0 ? "+---" : "+ ");
}
System.out.println("+");
for (int j = 0; j < x; j++) {
System.out.print((maze[j][i] & 8) == 0 ? "| " : "
}
System.out.println("|");
}

for (int j = 0; j < x; j++) {


System.out.print("+---");
}
System.out.println("+");
33

");

}
private void generateMaze(int cx, int cy) {
DIR[] dirs = DIR.values();
Collections.shuffle(Arrays.asList(dirs));
for (DIR dir : dirs) {
int nx = cx + dir.dx;
int ny = cy + dir.dy;
if (between(nx, x) && between(ny, y)
&& (maze[nx][ny] == 0)) {
maze[cx][cy] |= dir.bit;
maze[nx][ny] |= dir.opposite.bit;
generateMaze(nx, ny);
}}}
private static boolean between(int v, int upper) {
return (v >= 0) && (v < upper);
}
private enum DIR {
N(1, 0, -1), S(2, 0, 1), E(4, 1, 0), W(8, -1, 0);
private final int bit;
private final int dx;
private final int dy;
private DIR opposite;
static {
N.opposite = S;
S.opposite = N;
E.opposite = W;
W.opposite = E;
}
private DIR(int bit, int dx, int dy) {

34

this.bit = bit;
this.dx = dx;
this.dy = dy;
}
};
public static void main(String[] args) {
int x = args.length >= 1 ? (Integer.parseInt(args[0])) : 8;
int y = args.length == 2 ? (Integer.parseInt(args[1])) : 8;
MazeGenerator maze = new MazeGenerator(x, y);
maze.display();
}

35

OUTPUT

RESULT
Thus the program to implement maze generator is successsfully implemented and output
is verified.

36

Ex:No:4b
Date:

IMPLEMENTATION OF RECURSIVE
BACKTRACKING ALGORITHMS

AIM
To implement recursive backtracking algorithms using Dice generator.
ALGORITHM:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: Set diceRoll(dice - 1, chosen) to explore.
Step 4: Use Private recursive helper to implement diceSum logic.
Step 5: Parameter SumSoFar is used to sum the values of dice.
Step 6: In Recursive case dice >= 1, and it is possible to get the desired sum with this
many dice; and try choosing all possible values for the next 1 die..
Step 7: Display the result.
Step 8: Stop the program.

37

PROGRAM
import java.util.*;
public class Dice {
public static void main(String[] args) {
diceRoll(2);
System.out.println();
diceSum(3, 7);
}
public static void diceRoll(int dice) {
ArrayList list = new ArrayList();
diceRoll(dice, list);
}
private static void diceRoll(int dice, ArrayList chosen) {
if (dice == 0) {
System.out.println(chosen);
} else {
for (int i = 1; i<=6; i++) {
chosen.add(i); //choose
diceRoll(dice - 1, chosen); //explore
chosen.remove(chosen.size() - 1); //un-choose
}
}
}
// Prints all possible outcomes of rolling the given
38

// number of six-sided dice that add up to exactly


// the given sum, in [#, #, #] format.
// Example: diceSum(3, 10) will print [1, 5, 4], [3, 4, 4], ...
public static void diceSum(int dice, int n) {
ArrayList list = new ArrayList();
diceSum(dice, n, list, 0);
}
// Private recursive helper to implement diceSum logic.
// Adds a 'chosen' parameter of a list representing what dice values
// have been chosen so far, and a 'sumSoFar' parameter for the sum of
// all the dice rolls made so far.
// (The sumSoFar parameter avoids having to re-compute similar sums.)
private static void diceSum(int dice, int n, ArrayList chosen, int sumSoFar) {
if (dice == 0) {
// Base case; nothing left to roll. Maybe print what we chose.
if (sumSoFar == n) {
System.out.println(chosen);
}
} else if (sumSoFar < n && sumSoFar + 6 * dice >= n){
// Recursive case: dice >= 1, and it is possible
// to get the desired sum with this many dice;
// try choosing all possible values for the next 1 die
for (int i = 1; i<=6; i++) {

39

//choose
chosen.add(i);
sumSoFar += i;
//explore
diceSum(dice - 1, n, chosen, sumSoFar);
//unchoose
chosen.remove(chosen.size() - 1);
sumSoFar -= i;
}
}
}
}

40

OUTPUT

RESULT
Thus the program to implement sudoku is successfully executed and output is verified.

41

Ex:No:5a
Date:

IMPLEMENTATION OF RANDOMIZED
ALGORITHM-QUICK SORT

AIM:
To implement Randomized Quick sort algorithm.
AlGORITHM:
Step1: Start the program.
Step2: Declare the necessary variables.
Step3: Generate an integer array.
Step4:Rearrange the elements and split the array into two subarrays.
Step5: Generate middle element which is the pivot element.
Step6: Each element in the left subarray is less than or equal the middle element
Step7: Each element in the right subarray is greater than the middle element.
Step8: Recursively sort the two subarrays.
Step9: Stop the program
Step10: Resulting output gives the sorted elements of input ArrayList sorted
using divide and conquer method.

42

PROGRAM:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomizedQuickSort
{
public static void main(String[] args) {
RandomizedQuickSort app = new RandomizedQuickSort();
List<Integer> input = app.generateRandomNumbers(12);
System.out.println(input);
System.out.println(app.quicksort(input));
}
private List<Integer> quicksort(List<Integer> input){
if(input.size() <= 1)
{
return input;
}
int middle = (int) Math.ceil((double)input.size() / 2);
int pivot = input.get(middle);
List<Integer> less = new ArrayList<Integer>();
List<Integer> greater = new ArrayList<Integer>();

43

for (int i = 0; i < input.size(); i++)


{
if(input.get(i) <= pivot)
{
if(i == middle){
continue;
}
less.add(input.get(i));
}
Else
{
greater.add(input.get(i));
}
}
return concatenate(quicksort(less), pivot, quicksort(greater));
}
private List<Integer> concatenate(List<Integer> less, int pivot, List<Integer> greater){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < less.size(); i++) {
list.add(less.get(i));
}

44

list.add(pivot);
for (int i = 0; i < greater.size(); i++) {
list.add(greater.get(i));
}

return list;
}
private List<Integer> generateRandomNumbers(int n){
List<Integer> list = new ArrayList<Integer>(n);
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(n * 10));
}
return list;
}
}

45

OUTPUT

RESULT
Thus the program for implementing randomized algorithm has been compiled and
executed successfully.
46

Ex:No:5b

IMPLEMENTATION OF RANDOMIZED

Date:

ALGORITHM-RANDOM PASSWORD

AIM:
To write a java program to implement Random Password using Randomized Algorithm.
AlGORITHM:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: Create the class with specific name.
Step 4: Initialize the charset
Step 5: Using getrandomstring() get the length of the random string.
Step 6: If you generate more than 1 time, you must put the process to sleep for awhile
otherwise it will return the same random string.
Step 7: Display the result.
Step 8: Stop the program.

47

PROGRAM
import java.util.Random;
public class RandomString {
private static final String charset = "!@#$%^&*()" +
"0123456789" +
"abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String getRandomString(int length) {
Random rand = new Random(System.currentTimeMillis());
StringBuffer sb = new StringBuffer();
for (int i = 0; i <= length; i++ ) {
int pos = rand.nextInt(charset.length());
sb.append(charset.charAt(pos));
}
return sb.toString();
}
public static void main(String[] args) {
for (int i=0 ; i<10; i++){
System.out.println(RandomString.getRandomString(10));
try {
// if you generate more than 1 time, you must
// put the process to sleep for awhile
// otherwise it will return the same random string
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}}
}}

48

OUTPUT

RESULT
Thus the implementation of Randomized Algorithm using Random password is
successfully executed and verified

49

Ex:No:6a
Date:

IMPLEMENTATION OF LOCKING
MECHANISMS FOR CONCURRENT LINKED
LIST

AIM:
To implement locking mechanisms for linked list.
ALGORITHM:
Step 1: Create the final Lock class object lock from ReentrantLock class.
Step 2: Create the two threads and stat those threads.
Step 3: Try lock for thread block of code in run method if it is not locked using lock
object.
Step 4: Once the thread block is executed then unlocked the lock object.

50

PROGRAM
importjava.util.concurrent.TimeUnit;
importjava.util.concurrent.locks.Lock;
importjava.util.concurrent.locks.ReentrantLock;

public class ReentrantLockingDemo {


final Lock lock = new ReentrantLock();

public static void main(Stringargs[]) {


new ReentrantLockingDemo().go();
}

private void go() {


new Thread(newRunable(), "Thread1").start();
new Thread(newRunable(), "Thread2").start();
}

private Runnable newRunable() {


return new Runnable() {

@Override
public void run() {
do {
try {

if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
try {
System.out.println("locked thread "+ Thread.currentThread().getName());
Thread.sleep(1000);

} finally {
51

lock.unlock();
System.out.println("unlocked locked thread "
+ Thread.currentThread().getName());
}
break;
} else {
System.out.println("unable to lock thread "+
Thread.currentThread().getName() + " will re try again");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (true);
}
};
}
}

52

OUTPUT

RESULT
Thus the implementation of the locking mechanisms for Linked list is successfully
executed and verified.
53

Ex:No:6b
Date:

IMPLEMENTATION OF SYNCHRONIZATION
MECHANISMS FOR CONCURRENT LINKED
LIST

AIM
To implement Synchronization mechanisms for Concurrent linked list.
ALGORITHM
Step 1: Create the interface Linkable and declare two methods for both get and set
element in the list.
Step 2: Define Synchronized method of getHead() returns the first node in the list,
insertAtHead() to insert a node at the beginning of the list, insertAtTail() to insert
a node at the end of the list.
Step 3: Define Synchronized method of removeFromHead() to remove and return the
node at the head of the list and removeFromTail() to remove and return the node
at the end of the list.
Step 4: Define Synchronized method of remove to remove a node matching the specified
node from the list.
Step 5: The Test class is the nested class defines a main() method that tests the
LinkedList class.LinkedListclass create the object and insert some nodes.

54

PROGRAM
public class LinkedList {

public interface Linkable {

public Linkable getNext();

// Returns the next element in the list

public void setNext(Linkable node); // Sets the next element in the list
}

public synchronized Linkable getHead() {


return head;
}

public synchronized void insertAtHead(Linkable node) {


node.setNext(head);
head = node;
}

public synchronized void insertAtTail(Linkable node) {


if (head == null) {
head = node;
} else {
Linkable p, q;
for (p = head; (q = p.getNext()) != null; p = q);
p.setNext(node);
}
}

public synchronized Linkable removeFromHead() {


Linkable node = head;
55

if (node != null) {
head = node.getNext();
node.setNext(null);
}
return node;
}

public synchronized Linkable removeFromTail() {


if (head == null) {
return null;
}
Linkable p = head, q = null, next = head.getNext();
if (next == null) {
head = null;
return p;
}
while ((next = p.getNext()) != null) {
q = p;
p = next;
}
q.setNext(null);
return p;
}

public synchronized void remove(Linkable node) {


if (head == null) {
return;
}
if (node.equals(head)) {
head = head.getNext();
return;
56

}
Linkable p = head, q = null;
while ((q = p.getNext()) != null) {
if (node.equals(q)) {
p.setNext(q.getNext());
return;
}
p = q;
}
}

public static class Test {


static class LinkableInteger implements Linkable {
inti;

// The data contained in the node


Linkable next; // A reference to the next node in the list

publicLinkableInteger(inti) {
this.i = i;
}

// Constructor method

public Linkable getNext() {


return next;
}

// Part of Linkable

public void setNext(Linkable node) {


next = node;
} // Part of Linkable

public String toString() {


returni + "";
}

// For easy printing


57

publicboolean equals(Object o) {

// For comparison

if (this == o) {
return true;
}
if (!(o instanceofLinkableInteger)) {
return false;
}
if (((LinkableInteger) o).i == this.i) {
return true;
}

return false;
}
}

public static void main(String[] args) {


LinkedListll = new LinkedList();

// Create a list

ll.insertAtHead(new LinkableInteger(1)); // Insert some stuff


ll.insertAtHead(new LinkableInteger(2));
ll.insertAtHead(new LinkableInteger(3));
ll.insertAtHead(new LinkableInteger(4));
ll.insertAtTail(new LinkableInteger(5)); // Insert some more stuff
ll.insertAtTail(new LinkableInteger(6));
System.out.println(ll.removeFromHead()); // Remove and print a node
System.out.println(ll.removeFromTail()); // Remove and print another
ll.remove(new LinkableInteger(2));

// Remove another one

// Now print out the contents of the list.


for (Linkable l = ll.getHead(); l != null; l = l.getNext()) {
System.out.println(l);

} } } }
58

OUTPUT

RESULT
Thus the Synchronization mechanisms for Concurrent Linked lists is successfully
executed and verified.

59

Ex:No:6c
Date:

IMPLEMENTATION OF SYNCHRONIZATION
MECHANISMS FOR CONCURRENT QUEUE

AIM
To implement Synchronization mechanisms for Concurrent Queue.
ALGORITHM
Step 1: Create a shared queue object using LinkedBlockingQueue class.
Step 2: Create two threads for both Producer and Consumer and take the argument of
shared queue object.
Step 3: In Producer class the data item is to stored concurrently on shared queue using
the put() method.
Step 4: In Consumer class the data item is to take concurrently from the shared queue
using the take() method.

60

PROGRAM
importjava.util.concurrent.BlockingQueue;
importjava.util.concurrent.LinkedBlockingQueue;
importjava.util.logging.Level;
importjava.util.logging.Logger;

public class ConcurrentQueue {


public static void main(String args[]){

//Creating shared object


BlockingQueuesharedQueue = new LinkedBlockingQueue();

//Creating Producer and Consumer Thread


Thread prodThread = new Thread(new Producer(sharedQueue));
Thread consThread = new Thread(new Consumer(sharedQueue));

prodThread.start();
consThread.start();
}
}

//Producer Class in java


class Producer implements Runnable {

private final BlockingQueuesharedQueue;


public Producer(BlockingQueuesharedQueue) {
this.sharedQueue = sharedQueue;
}

61

@Override
public void run() {
for(inti=0; i<10; i++){
try {
System.out.println("Produced: " + i);
sharedQueue.put(i);
} catch (InterruptedException ex) {
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
}

//Consumer Class in Java


class Consumer implements Runnable{

private final BlockingQueuesharedQueue;

public Consumer (BlockingQueuesharedQueue) {


this.sharedQueue = sharedQueue;
}

@Override
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); } } }}

62

OUTPUT

RESULT
Thus the Synchronization mechanisms for Concurrent Queue is successfully executed
and verified.

63

Ex:No:6d
Date:

IMPLEMENTATION OF SYNCHRONIZATION
MECHANISMS FOR CONCURRENT STACK

AIM
To implement Synchronization mechanisms for Concurrent Stack.
ALGORITHM
Step 1: Create a shared queue object using ConcurrentLinkedDequeclass.
Step 2: Create two threads for both Producer and Consumer and take the argument of
shared queue object.
Step 3: In Producer class the data item is to stored concurrently on shared queue using
the put() method.
Step 4: In Consumer class the data item is to take concurrently from the shared queue
using the take() method.

64

PROGRAM
importjava.util.concurrent.ConcurrentLinkedDeque;
importjava.util.logging.Level;
importjava.util.logging.Logger;

public class ConcurrentStack {


public static void main(String[] args) {

ConcurrentLinkedDequesharedStack = new ConcurrentLinkedDeque<String>();

Producer producer = new Producer(sharedStack);


Consumer consumer = new Consumer(sharedStack);

new Thread(producer).start();
new Thread(consumer).start();
}
}

class Producer implements Runnable {

publicConcurrentLinkedDequesharedStack = null;

public Producer(ConcurrentLinkedDeque<String>sharedStack) {
this.sharedStack = sharedStack;
}

@Override
public void run() {
try {
sharedStack.push("1");
65

sharedStack.push("2");
sharedStack.push("3");
sharedStack.push("4");
sharedStack.push("5");
} catch (Exception ex) {
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}

class Consumer implements Runnable {

publicConcurrentLinkedDequesharedStack = null;

public Consumer(ConcurrentLinkedDeque<String>sharedStack) {
this.sharedStack = sharedStack;
}

@Override
public void run() {
try {
System.out.println("Elements in the Concurrent Stack");

while(!sharedStack.isEmpty()) {
System.out.println(sharedStack.pop());
}
} catch (Exception ex) {
Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE,
null, ex); } } }

66

OUTPUT

RESULT
Thus the Synchronization mechanisms for Concurrent Stack is successfully executed and
verified.
67

Ex:No:7
Date:

IMPLEMENTATION OF DEVELOPING
APPLICATIONS INVOLVING CONCURRENCY

AIM
To develop applications involving Concurrency.
ALGORITHM
Step 1: Declare the thread size and thread pool size with respective variable.
Step 2: Create the ExecutorService using its method newFixedThreadPool and take the
argument of thread pool size.
Step 3: Create WorkerThread object with number of workers as the argument and
executeExecutorService using execute method and when execution is completed
Executor Service should be closed using the shutdown() method.
Step 4: Work is performed concurrently in WorkerThread class in run() method.

68

PROGRAM
// WorkerThread.java
public class WorkerThread implements Runnable {
privateintworkerNumber;
WorkerThread(int number) {
workerNumber = number; }
public void run() {
for (inti=0;i<=100;i+=20) {
// Perform some work ...
System.out.println("Worker number: " + workerNumber+ ", percent complete: " + i );
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) { }
}}}
// TheadPoolTest.java
importjava.util.concurrent.*;
public class ThreadPoolTest {
public static void main(String[] args) {
intnumWorkers = Integer.parseInt(args[0]);
intthreadPoolSize = Integer.parseInt(args[1]);
ExecutorServicetpes =Executors.newFixedThreadPool(threadPoolSize);
WorkerThread[] workers = new WorkerThread[numWorkers];
for (inti = 0; i<numWorkers; i++) {
workers[i] = new WorkerThread(i);
tpes.execute(workers[i]);
}
tpes.shutdown();
} }
// java ThreadPoolTest 4 2 (4 workers and a pool of 2 threads)

69

OUTPUT

RESULT
Thus the developing application involving Concurrency is successfully executed and
verified.
70

You might also like