advanced ada lab manual m-tech vtu

31
Advanced Algorithms Laboratory (14SCS26) Experiment No: 1 Title of the Experiment : Design, develop and run program in any language to implement the Bellman-Ford algorithm and determine its performance. Objective of the Experiment : To solve the single-source shortest-paths problem using Bellman-Ford algorithm. Theory: Given a weighted, directed graph G=(V,E) with s and weight function w:E→R,the Bellman Ford algorithm returns a Boolean value indicating whether or not there is negative- weight cycle that is reachable from the source. If there is such a cycle, the algorithm indicates that no solution exists. If there is no such cycle, the algorithm produces the shortest paths and their weights. Algorithm : Bellman-Ford (G,w,s) 1 INITIALIZE-SINGLE-SOURCE(G,s) 2 for i=1 to |G.V| - 1 3 for each edge (u,v) € G.E 4 RELAX(u,v,w) 5 for each edge (u,v) € G.E 6 if v.d > u.d +w(u,v) 7 return FALSE 8 return TRUE Source Code: import java.util.Scanner; public class BellmanFord { private int distances[]; private int numberofvertices; public static final int MAX_VALUE = 999; 1 Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Upload: mallesh-kumar

Post on 09-Jul-2016

336 views

Category:

Documents


82 download

DESCRIPTION

Contains all lab programs in java

TRANSCRIPT

Page 1: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

Experiment No: 1 Title of the Experiment :Design, develop and run program in any language to implement the Bellman-Ford algorithm and determine its performance.Objective of the Experiment :To solve the single-source shortest-paths problem using Bellman-Ford algorithm.

Theory: Given a weighted, directed graph G=(V,E) with s and weight function w:E→R,the Bellman

Ford algorithm returns a Boolean value indicating whether or not there is negative-weight cycle that is reachable from the source. If there is such a cycle, the algorithm indicates that no solution exists. If there is no such cycle, the algorithm produces the shortest paths and their weights.

Algorithm :

Bellman-Ford (G,w,s)1 INITIALIZE-SINGLE-SOURCE(G,s)2 for i=1 to |G.V| - 13 for each edge (u,v) € G.E4 RELAX(u,v,w)5 for each edge (u,v) € G.E6 if v.d > u.d +w(u,v)7 return FALSE8 return TRUESource Code:

import java.util.Scanner;

public class BellmanFord{

private int distances[];private int numberofvertices;public static final int MAX_VALUE = 999;

public BellmanFord(int numberofvertices){

this.numberofvertices = numberofvertices;distances = new int[numberofvertices + 1];

}

public void BellmanFordEvaluation(int source, int adjacencymatrix[][]){

boolean isNegCycle = false;1

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 2: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

for (int node = 1; node <= numberofvertices; node++){

distances[node] = MAX_VALUE;}

distances[source] = 0;for (int node = 1; node <= numberofvertices - 1; node++){

for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++){

for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)

{

if ((distances[sourcenode] + adjacencymatrix[sourcenode][destinationnode]) < distances[destinationnode])

{distances[destinationnode] = distances[sourcenode] +

adjacencymatrix[sourcenode][destinationnode];}

}}

}

for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++){

for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)

{if ((distances[sourcenode] + adjacencymatrix[sourcenode]

[destinationnode]) < distances[destinationnode]){

isNegCycle = true;System.out.println("The Graph contains negative egde cycle");break;

}}if (isNegCycle)

break;}

if (!isNegCycle){

for (int vertex = 1; vertex <= numberofvertices; vertex++){

2

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 3: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

System.out.println("distance of source " + source + " to "+ vertex + " is " + distances[vertex]);

}}

}

public static void main(String... arg){

int numberofvertices = 0;int source;

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the number of vertices");numberofvertices = scanner.nextInt();

int adjacencymatrix[][] = new int[numberofvertices + 1][numberofvertices + 1];System.out.println("Enter the adjacency matrix");for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++){

for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)

{adjacencymatrix[sourcenode][destinationnode] = scanner.nextInt();

if ((sourcenode != destinationnode) && (adjacencymatrix[sourcenode][destinationnode] == 0))

{adjacencymatrix[sourcenode][destinationnode] = MAX_VALUE;

}}

}

System.out.println("Enter the source vertex");source = scanner.nextInt();

BellmanFord bellmanford = new BellmanFord(numberofvertices);bellmanford.BellmanFordEvaluation(source, adjacencymatrix);scanner.close();

}}

3

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 4: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

Results: 1.Input:Enter the number of vertices4Enter the adjacency matrix1 2 3 45 6 7 89 10 11 1213 14 15 16Enter the source vertex4

Output:Program Started AT : Sun May 15 12:53:01 IST 2016Distance of Source 4 to 1 is 13Distance of Source 4 to 2 is 14Distance of Source 4 to 3 is 15Distance of Source 4 to 4 is 0Program Ended AT : Sun May 15 12:53:01 IST 2016

Performance Parameters:Time Taken By the Program to Run : 0 msNumber of Iterations taken By the Program to Run : 11

2. Input:For the directed Graph

Enter the number of vertices4Enter the adjacency matrix0 1 999 999999 999 999 9992 1 0 11 2 999 0

4

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 5: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

Enter the source vertex3

Output:Program Started AT : Sun May 15 13:25:55 IST 2016Distance of Source 3 to 1 is 2Distance of Source 3 to 2 is 1Distance of Source 3 to 3 is 0Distance of Source 3 to 4 is 1Program Ended AT : Sun May 15 13:25:55 IST 2016

Performance Parameters:Time Taken By the Program to Run : 0 msNumber of Iterations taken By the Program to Run : 11

5

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 6: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

Experiment No : 2

Title of the Experiment:Design, develop and run a program in any language to implement a Miller Rabin / Monte Carlo algorithm to test the primality of a given integer and determine its performance.

Objective of the Experiment :Miller Rabin Algorithms always gives an answer, but there is a probability of being completely wrong.

Theory: o There are problems for which no efficient algorithm is known, and

Approximate solutions do not make sense.o A Miller Rabin Primality Test/ Monte Carlo algorithm always gives an answer but

occasionally makes a mistake.o But it finds a correct solution with high probability whatever the instance is processed, i.e.

there is no instance on which the probability of error is high.o However, no warning is usually given when the algorithm gives a wrong solution.

Algorithm :

Miller Rabin Primality Test MC Algorithm

function MillerRabinPrimalityTest(n)Input: n (an odd positive integer) Output: .true. Or .false. (Always correct when .false. Is returned, and correct at least 75% when .true. is returned)a ß Random(2, n-2)find positive integers k, m such that n-1 =2k m, and m oddb ßam mod n for j ß 1 to k doif b ≠ 1 .and. b ≠ n-1 then return(.false.)else

if b = n-1 then return(.true.) endif endif b ß b*b mod nendfor If b ≠ 1 then return(.false.) else return(.true.) endif end MillerRabinPrimalityTest

Source Code:

6

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 7: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

import java.math.BigInteger;import java.util.Random;import java.util.Scanner;

public class MillerRabin{

// Reference: Section 31.6, Page no: 957// This method returns (a^u) modulo npublic long ModularExpo(long a, long u, long n){

int i; long d = 1; // Below statement is to find out the number of bits in the number int k = (int)Math.floor(Math.log(u) / Math.log(2)); for (i = k; i >= 0; i--) { d = (d*d)%n; if (BigInteger.valueOf(u).testBit(i)) //Check if ith bit is set d = (d*a)%n; } return d;

}// Reference: Section 31.8, Page no: 969// This function returns // - true, if the number is composite// - false, if the number is primepublic boolean witness(long a, long n){

long t = 0, u = n-1;

// Value n-1 needs to be represented in the below format// n-1 = (2^t).u, where u is odd number// Below while loop finds the value of t and u while(true){

if ((u%2)==0){

t++;u = u/2;

}else

break;}

7

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 8: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

long []x = new long[(int)t+1];int i;x[0] = ModularExpo(a, u, n);for (i = 1; i <= t; i++){

x[i] = (x[i-1]*x[i-1])%n;if ((x[i] == 1) && (x[i-1] != 1) && (x[i-1] != (n-1))) // Check for non-trivial

square root modulo n{

return true;}

}if (x[(int)t] == 1) // Is a^(n-1)=1 (modulo n)

return false;else

return true;}public boolean isPrime(long n, int s){

Random rand = new Random();for (int j = 1; j <= s; j++){

long r = Math.abs(rand.nextLong()); // Generates random numberlong a = r%(n); // try to restrict the random number to n-1if (witness(a, n)){

return false;}

}return true;

}public static void main(String[] args){

long n;int s;MillerRabin mr = new MillerRabin();Scanner sc = new Scanner(System.in);

System.out.println("Enter a number:");n = sc.nextLong();System.out.println("Enter no of iterations:");s = sc.nextInt();

if (mr.isPrime(n, s))System.out.println("Number is probably prime");

else8

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 9: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

System.out.println("Number is composite ");

sc.close();}

}Results: 1.Input:Enter a number:3Enter no of iterations:1

Output:Program Started AT : Sun May 15 13:40:45 IST 2016Number is probably primeProgram Ended AT : Sun May 15 13:40:45 IST 2016

Performance Parameters:Time Taken By the Program to Run : 0 msNumber of Iterations taken By the Program to Run : 2

1.Input:Enter a number:4Enter no of iterations:1

Output:Program Started AT : Sun May 15 13:40:45 IST 2016Number is CompositeProgram Ended AT : Sun May 15 13:40:45 IST 2016

Performance Parameters:Time Taken By the Program to Run : 0 msNumber of Iterations taken By the Program to Run : 2

9

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 10: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

Experiment No: 3

Title of the Experiment:Design, develop and run program in any language to solve the string matching problem using naïve approach and the KMP algorithm and compare their performances. Objective of the Experiment :

To solve the string matching problem using Naïve and Knuth Morris Pratt algorithm and compare their performances.

Theory: Components of KMP algorithm

The prefix function, Π The prefix function,Π for a pattern encapsulates knowledge about how the pattern matches

against shifts of itself. This information can be used to avoid useless shifts of the pattern ‘p’. In other words, this enables avoiding backtracking on the string ‘S’.

The KMP Matcher With string ‘S’, pattern ‘p’ and prefix function ‘Π’ as inputs, finds the occurrence of ‘p’ in

‘S’ and returns the number of shifts of ‘p’ after which occurrence is found.

Algorithm :

Naïve AlgorithmNAÏVE-STRING-MATCHER(T,P)1 n=T.length2 m=P.length3 for s=0 to n-m4 if P[1..m] == T[s+1..s+m]5 print “Pattern occurs with shift” s

The prefix function, ΠFollowing pseudo code computes the prefix function, Π:

1 m ß length[p] //’p’ pattern to be matched2 Π[1] ß 0 3 k ß 0 4 for q ß 2 to m5 do while k > 0 and p[k+1] != p[q]

10

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 11: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

6 do k ß Π[k]7 If p[k+1] = p[q]8 then k ß k +19 Π[q] ß k10 return Π

In the above pseudo code for computing the prefix function, the for loop from step 4 to step 10 runs ‘m’ times. Step 1 to step 3 take constant time. Hence the running time of compute prefix function is Θ (m).

KMP Matcher

1 n ß length[S] 2 m ß length[p]3 Π ß Compute-Prefix-Function(p)4 q ß 0 5 for i ß 1 to n 6 do while q > 0 and p[q+1] != S[i]

7 do q ß Π[q] 8 if p[q+1] = S[i]9 then q ß q + 1 10 if q = m 11 then print “Pattern occurs with shift” i – m12 q ß Π[ q]

The for loop beginning in step 5 runs ‘n’ times, i.e., as long as the length of the string ‘S’. Since step 1 to step 4 take constant time, the running time is dominated by this for loop. Thus running time of matching function is Θ(n).

Source Code:

Naïve Algorithm

import java.util.*;public class Naive {

public static void main(String[] args){ try{

String text, pattern;int i, j,lcount = 0;Scanner in = new Scanner(System.in);System.out.println("Enter text");text = in.nextLine();System.out.println("Enter pattern:");pattern = in.nextLine();

11

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 12: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

in.close();Date date1 = new Date();

System.out.println("Program Started AT : " + date1); long start = System.currentTimeMillis( );

boolean found = false;for (i = 0; i <= (text.length()-pattern.length()); i++){

for (j = 0; j < pattern.length(); j++){

if (text.charAt(i+j) != pattern.charAt(j))break;

lcount++;}if (j == pattern.length()){

found = true;System.out.println("Matching found at "+ (i+1));

}}if (found == false){

System.out.println("Pattern not found");}

Date date2 = new Date(); System.out.println("Program Ended AT : " + date2); long end = System.currentTimeMillis( ); long diff = end - start;

System.out.println("Time Taken By the Program to Run : " + diff + " ms"); System.out.println("Number of Iterations taken By the Program to Run : " + lcount); }catch (Exception e) {

System.out.println("Got an exception!"); }

}}

KMP Algorithm

/** ** Java Program to implement Knuth Morris Pratt Algorithm **/ import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.IOException;

12

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 13: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

/** Class KnuthMorrisPratt **/public class KMP{

private int[] pi; // Prefix Function private int n; // text length private int m; // pattern length; /** Constructor **/ public KMP(String text, String pat) { n = text.length(); m = pat.length(); pi = new int[pat.length()+1]; computePrefixFunction(pat); int q = 0; boolean patFound = false; for (int i = 0; i < n; i++) { while ((q > 0) && pat.charAt(q) != text.charAt(i)) { q = pi[q]; } if (pat.charAt(q) == text.charAt(i)) { q = q+1; } if (q == m) { System.out.println("Pattern found at location: "+(i-m+2)); q = pi[q]; patFound = true; } } if (!patFound) { System.out.println("Pattern not found"); } }

private void computePrefixFunction(String pat) { pi[1] = 0; int k = 0; for (int q = 1; q < m; q++)

13

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 14: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

{ while ((k > 0) && pat.charAt(k) != pat.charAt(q)) { k = pi[k]; } if (pat.charAt(k) == pat.charAt(q)) { k = k+1; } pi[q+1] = k; } }

/** Main Function **/ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Knuth Morris Pratt Test"); System.out.println("Enter Text"); String text = br.readLine(); System.out.println("Enter Pattern"); String pattern = br.readLine(); new KMP(text, pattern); }}Results:

Naïve Algorithm

Input:Enter textHello WorldEnter pattern:Wor

Output:Program Started AT : Sun May 15 19:27:07 IST 2016Matching found at 7Program Ended AT : Sun May 15 19:27:07 IST 2016

Performance Parameters:Time Taken By the Program to Run : 0 msNumber of Iterations taken By the Program to Run : 3

Input:14

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 15: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

Enter textBasavesvara Engineering CollegeEnter pattern:college

Output:Program Started AT : Sun May 15 19:29:56 IST 2016Pattern not foundProgram Ended AT : Sun May 15 19:29:56 IST 2016

Performance Parameters:Time Taken By the Program to Run : 0 msNumber of Iterations taken By the Program to Run : 0

KMP Algorithm

Input:Knuth Morris Pratt TestEnter TextHello WorldEnter PatternWor

Output:Program Started AT : Sun May 15 14:52:17 IST 2016Pattern found at location: 7Program Ended AT : Sun May 15 14:52:17 IST 2016

Performance Parameters:Time Taken By the Program to Run : 1 msNumber of Iterations taken By the Program to Run : 13

Input: Knuth Morris Pratt TestEnter TextBasavesvara Engineering CollegeEnter Patterncollege

Output:Program Started AT : Sun May 15 15:00:24 IST 2016Pattern not foundProgram Ended AT : Sun May 15 15:00:24 IST 2016

Performance Parameters:Time Taken By the Program to Run : 0 msNumber of Iterations taken By the Program to Run : 37

15

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 16: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

Comparison between KMP & Naïve AlgorithmsBy seeing the output & performance in both the examples it is clear that Naïve algorithm is most efficient than KMP

Experiment No: 4

Title of the ExperimentDesign, develop and write program to solve string matching problem using Finite Automata and determine its performance.Theory:

In FA based algorithm, we preprocess the pattern and build a 2D array that represents a Finite Automata. Construction of the FA is the main tricky part of this algorithm. Once the FA is built, the searching is simple. In search, we simply need to start from the first state of the automata and first character of the text. At every step, we consider next character of text, look for the next state in the built FA and move to new state. If we reach final state, then pattern is found in text. Time complexity of the search prcess is O(n).

16

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 17: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

Before we discuss FA construction, let us take a look at the following FA for pattern ACACAGA.

The above diagrams represent graphical and tabular representations of pattern ACACAGA.

Number of states in FA will be M+1 where M is length of the pattern. The main thing to construct FA is to get the next state from the current state for every possible character

Algorithm:FINITE-AUTOMATON-MATCHER(T, , m)1 n length[T]2 q 03 for i 1 to n4 do q (q, T[i])5 if q = m6 then s i - m7 print "Pattern occurs with shift" s

Source Code:import java.io.*;

public class FiniteAutomata {

int[][] TF;public int getNextState(String p, int m, int q, int x){

17

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 18: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

int i;if ((q < m) && (p.charAt(q)==x))

return q+1;

for (int ns = q; ns > 0; ns--){

if (p.charAt(ns-1) == x){

for (i = 0; i < ns-1; i++){

if (p.charAt(i) != p.charAt(q-ns+i+1)){

break;}

}if (i == ns-1)

return ns;}

}return 0;

}

public void computeTF(String p, int m, int[][]TF){

for (int q=0; q<=m; q++){

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

TF[q][x] = getNextState(p, m, q, x);}

}}

public void search(String text, String pattern){

int n = text.length();int m = pattern.length();int [][] TF = new int[m+1][256];computeTF(pattern, m, TF);

int ns = 0;boolean found = false;for (int i = 0; i < n; i++){

ns = TF[ns][text.charAt(i)];if (ns==m)

18

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 19: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

{found = true;System.out.println("Pattern found at "+(i-m+2));

}}if (found == false){

System.out.println("Pattern not found");}

}public static void main(String[] args) throws Exception{

FiniteAutomata fa = new FiniteAutomata();String text, pattern;BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter text:");text = reader.readLine();System.out.println("Enter pattern:");pattern = reader.readLine();fa.search(text, pattern);

}}Input:Enter text:Hello WorldEnter pattern:World

Output:Program Started AT : Sun May 15 15:07:26 IST 2016Pattern found at 7Program Ended AT : Sun May 15 15:07:26 IST 2016

Performance Parameters:Time Taken By the Program to Run : 1 msNumber of Iterations taken By the Program to Run : 1567

Input:Enter text:Finite AutomataEnter pattern:ataa

Output:Program Started AT : Sun May 15 15:09:20 IST 2016

19

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 20: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

Pattern not foundProgram Ended AT : Sun May 15 15:09:20 IST 2016

Performance Parameters:Time Taken By the Program to Run : 1 msNumber of Iterations taken By the Program to Run : 1301

Experiment No: 5Title of the ExperimentDesign, develop and write program to solve string matching problem using Robin Karp algorithm and determine its performance.Theory:

Rabin-Karp algorithm slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings.

1) Pattern itself.

20

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 21: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

2) All the substrings of text of length m.

Since we need to efficiently calculate hash values for all the substrings of size m of text, we must have a hash function which has following property.Hash at the next shift must be efficiently computable from the current hash value and next character in text or we can say hash(txt[s+1 .. s+m]) must be efficiently computable from hash(txt[s .. s+m-1]) and txt[s+m] i.e., hash(txt[s+1 .. s+m])= rehash(txt[s+m], hash(txt[s .. s+m-1]) and rehash must be O(1) operation.

The hash function suggested by Rabin and Karp calculates an integer value. The integer value for a string is numeric value of a string. For example, if all possible characters are from 1 to 10, the numeric value of “122” will be 122. The number of possible characters is higher than 10 (256 in general) and pattern length can be large. So the numeric values cannot be practically stored as an integer. Therefore, the numeric value is calculated using modular arithmetic to make sure that the hash values can be stored in an integer variable (can fit in memory words). To do rehashing, we need to take off the most significant digit and add the new least significant digit for in hash value. Rehashing is done using the following formula.

hash( txt[s+1 .. s+m] ) = d ( hash( txt[s .. s+m-1]) – txt[s]*h ) + txt[s + m] ) mod q

hash( txt[s .. s+m-1] ) : Hash value at shift s.hash( txt[s+1 .. s+m] ) : Hash value at next shift (or shift s+1)d: Number of characters in the alphabetq: A prime numberh: d^(m-1)

Algorithm:function RabinKarpSet(string s[1..n], set of string subs, m): set hsubs := emptySet foreach sub in subs insert hash(sub[1..m]) into hsubs hs := hash(s[1..m]) for i from 1 to n-m+1 if hs ∈ hsubs and s[i..i+m-1] ∈ subs return i hs := hash(s[i+1..i+m]) return not found

Source Code:import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Scanner;public class RabinKarp {

public void search(String T, String P, int d, int q)

21

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 22: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

{int n, m, h, p, i;

n = T.length();m = P.length();int []t = new int[n];h = 1;for (i = 1; i <= m-1; i++)

h = (h*d) % q;p = 0;t[0] = 0;boolean found = false;for (i = 0; i < m; i++){

p = (d*p + (P.charAt(i)-48))%q;t[0] = (d*t[0]+(T.charAt(i)-48))%q;

}

for (int s = 0; s <= n-m; s++){

if (p == t[s]){

for (i = 0; i < m; i++){

if (P.charAt(i) != T.charAt(s+i)){

break;}

}if (i == m){

found = true;System.out.println("Pattern found at :"+(s+1));

}}if (s < n-m){

t[s+1] = (d*(t[s]-(T.charAt(s)-48)*h)+(T.charAt(s+m)-48)) % q;if (t[s+1] < 0)

t[s+1] += (q);

}}if (found == false){

22

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 23: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

System.out.println("Pattern not found");}

}public static void main(String[] args) throws Exception{

String text, pattern;int d, q;RabinKarp rk = new RabinKarp();BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter text:");text = reader.readLine();System.out.println("Enter pattern:");pattern = reader.readLine();

Scanner sc = new Scanner(System.in);System.out.println("Enter base:");d = sc.nextInt();System.out.println("Enter prime number:");q = sc.nextInt();rk.search(text, pattern, d, q);sc.close();

}

}Input:Enter text:Hello WorldEnter pattern:WorEnter base:2Enter prime number:3Output:Program Started AT : Sun May 15 15:14:49 IST 2016Pattern found at :7Program Ended AT : Sun May 15 15:14:49 IST 2016

Performance Parameters:Time Taken By the Program to Run : 1 msNumber of Iterations taken By the Program to Run : 20

Input:Enter text:Hello Worlds

23

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot

Page 24: Advanced ADA Lab Manual M-Tech VTU

Advanced Algorithms Laboratory (14SCS26)

Enter pattern:Hello WorldnEnter base:2Enter prime number:3Output:Program Started AT : Sun May 15 15:14:49 IST 2016Pattern Not found Program Ended AT : Sun May 15 15:14:49 IST 2016

Performance Parameters:Time Taken By the Program to Run : 1 msNumber of Iterations taken By the Program to Run : 24

24

Dept of Computer Science & Engineering, Basaveshwar Engineering College, Bagalkot