Welcome to my blog

Wednesday, 29 November 2017

10 a. IMPLEMENTATION OF ACTIVITY SELECTION



10 a. IMPLEMENTATION OF ACTIVITY SELECTION

AIM:
      To write a java program to implement Activity Selection.


ALGORITHM:
  1.Sort the activities as per finishing time in ascending order
  2.Select the first activity
  3.Select the new activity if its starting time is greater than or equal to the previously selected        activity
   4.REPEAT step 3 till all activities are checked


PROGRAM :
import java.util.*;
import java.lang.*;
import java.io.*;
class ActivitySelection
{
public static void printMaxActivities(int s[], int f[], int n)
{
int i, j;
System.out.print("Following activities are selected : n");
i = 0;
System.out.print(i+" ");
for (j = 1; j < n; j++)
{
if (s[j] >= f[i])
{
System.out.print(j+" ");
i = j;
}
}
}
public static void main(String[] args)
{
int s[] =  {1, 3, 0, 5, 8, 5};
int f[] =  {2, 4, 6, 7, 9, 9};
int n = s.length;
printMaxActivities(s, f, n);
}

9. IMPLEMENTATION OF MATRIX CHAIN MULTIPLICATION





9. IMPLEMENTATION OF MATRIX CHAIN MULTIPLICATION


AIM: 
To write a java program to implement Matrix Chain Multiplication.

ALGORITHM:
  1. A chain of matrices to be multiplied is given as input.
  2. For a sequence A1,A2,A3,A4 of 4 matrices, there are 5 different orderings=5 different parethesization.
i)                    (A1,(A2(A3 A4)))
ii)                  (A1((A2 A3)A4))
iii)                ((A1 A2)(A3 A4))
iv)                ((A1(A2 A3))A4)
v)                  (((A1 A2)A3)A4)
  1. Matrix_Multiply(A,B)
       If coloumns[A]!=rows[B]
            Then error “incomplete dimensions”
            Else for i <- 1 to rows[A]
              Do for j <- 1 to columns[B]
                   Do c[I,j] <- 0
                        For k<- 1 to columns[A]
                        Do c[i,j]=C[i,j]+A[i,k]+B[i,j]
                        Return c
  1.    A parenthesizing of the chain of the matrices is obtained as output.
PROGRAM :
public class MatrixChainMulti
{
void matrixchain(int a[])
{
int q;
int n=a.length;
int m[][]=new int[n][n];
int s[][]=new int[n][n];
for (int i=1;i<n;i++)
m[i][i]=0;
for (int l=2;l<n;l++) //l is the length
{
for(int i=1 ;i<n-l+1;i++)
{
int j=i+l-1;
m[i][j]=Integer.MAX_VALUE;
for (int k=i ;k<=j-1;k++)
{
q=m[i][k]+m[k+1][j]+a[i-1]*a[k]*a[j];
if(q<m[i][j])
{
m[i][j]=q;
s[i][j]=k;
}
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(m[i][j]+" ");
System.out.println();
}
print_optimal(s,1,6);
}
void print_optimal(int s[][],int i,int j)
{
if (i==j)
System.out.print("A"+i);
else
{
System.out.print("(");
print_optimal(s,i,s[i][j]);
print_optimal(s,s[i][j]+1,j);
System.out.print(")");
}
}
public static void main(String args[])
{
int a[]={30, 35, 15, 5, 10, 20, 25};//A1:-30x35, A2:- 35x15, A3:- 15x5, A4:- 5x10 , A5:- 10x20, A6:- 20x25
MatrixChainMulti n=new MatrixChainMulti();
n.matrixchain(a);
}
}


8b. IMPLEMENTATION OF BELLMANFORD ALGORITHM




8b. IMPLEMENTATION OF BELLMANFORD ALGORITHM

AIM:
To write a java program to implement quick sort.

ALGORITHM:
  1. Start with the weighted graph
              2.Choose the starting vertex and assign infinity path values to all other vertex      
         3.Visit each edge and relax  the path distance if they are inaccurate
  4.We need to do this V times because in the worst case the vertex path length might need to       be readjusted V times
  5.Notice how the vertex at the top right corner had its path length adjusted
  6.After all vertices  have their path lengths we check if a negative cycle is present

PROGRAM :
import java.util.Scanner;
public class MergeSort
{
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
sort(a, low, mid);
sort(a, mid, high);
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Merge Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
sort(arr, 0, n);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}

8a. DIJKSTRAS ALGORITHM





8a. DIJKSTRAS ALGORITHM
AIM:
      To write a java program to implement Dijkstra Algorithm.

ALGORITHM:
1.Initialization of all nodes with distance "infinite"; initialization of the starting node with 0
2.Marking of the distance of the starting node as permanent, all other distances as temporarily.
3.Setting of starting node as active.
4.Calculation of the temporary distances of all neighbour nodes of the active node by summing up its distance with the weights of the edges.
5.If such a calculated distance of a node is smaller as the current one, update the distance and set the current node as antecessor. This step is also called update and is Dijkstra's central idea.
6.Setting of the node with the minimal temporary distance as active. Mark its distance as permanent.
Repeating of steps 4 to 7 until there aren't any nodes left with a permanent distance, which neighbours still have temporary distance

PROGRAM:
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class DijkstraAlgorithmSet
{
private int distances[];
private Set<Integer> settled;
private Set<Integer> unsettled;
private int number_of_nodes;
private int adjacencyMatrix[][];
public DijkstraAlgorithmSet(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
settled = new HashSet<Integer>();
unsettled = new HashSet<Integer>();
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
for (int i = 1; i <= number_of_nodes; i++)
{
distances[i] = Integer.MAX_VALUE;
}
unsettled.add(source);
distances[source] = 0;
while (!unsettled.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
unsettled.remove(evaluationNode);
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getNodeWithMinimumDistanceFromUnsettled()
{
int min ;
int node = 0;
Iterator<Integer> iterator = unsettled.iterator();
node = iterator.next();
min = distances[node];
for (int i = 1; i <= distances.length; i++)
{
if (unsettled.contains(i))
{
if (distances[i] <= min)
{
min = distances[i];
node = i;
}
}
}
return node;
}
private void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;
for (int destinationNode = 1; destinationNode <= number_of_nodes; destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE)
{
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
}
unsettled.add(destinationNode);
}
}
}
}
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();
DijkstraAlgorithmSet dijkstrasAlgorithm = new DijkstraAlgorithmSet(number_of_vertices);
dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix, source);
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();
}
}