Está en la página 1de 25

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:ER,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;
public BellmanFord(int numberofvertices)
{
this.numberofvertices = numberofvertices;
distances = new int[numberofvertices + 1];
}
public void BellmanFordEvaluation(int source, int adjacencymatrix[][])
{
1
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


boolean isNegCycle = false;
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)
{
2
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


for (int vertex = 1; vertex <= numberofvertices; vertex++)
{
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

Advanced Algorithms Laboratory (14SCS26)

Results:
1.
Input:
Enter the number of vertices
4
Enter the adjacency matrix
1234
5678
9 10 11 12
13 14 15 16
Enter the source vertex
4
Output:
Program Started AT : Sun May 15 12:53:01 IST 2016
Distance of Source 4 to 1 is 13
Distance of Source 4 to 2 is 14
Distance of Source 4 to 3 is 15
Distance of Source 4 to 4 is 0
Program Ended AT : Sun May 15 12:53:01 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 0 ms
Number of Iterations taken By the Program to Run : 11
2. Input:
For the directed Graph

Enter the number of vertices


4
Enter the adjacency matrix
0 1 999 999
999 999 999 999
2101
4
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


1 2 999 0
Enter the source vertex
3
Output:
Program Started AT : Sun May 15 13:25:55 IST 2016
Distance of Source 3 to 1 is 2
Distance of Source 3 to 2 is 1
Distance of Source 3 to 3 is 0
Distance of Source 3 to 4 is 1
Program Ended AT : Sun May 15 13:25:55 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 0 ms
Number of Iterations taken By the Program to Run : 11

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

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 odd
b am mod n
for j 1 to k do
if b 1 .and. b n-1 then return(.false.)
else
if b = n-1 then return(.true.) endif
endif
b b*b mod n
endfor
If b 1 then return(.false.) else return(.true.) endif
6
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


end MillerRabinPrimalityTest
Source Code:
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 n
public 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 prime
public 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++;
7
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


u = u/2;
}
else
break;
}
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 number
long a = r%(n); // try to restrict the random number to n-1
if (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();
8
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


System.out.println("Enter no of iterations:");
s = sc.nextInt();
if (mr.isPrime(n, s))
System.out.println("Number is probably prime");
else
System.out.println("Number is composite ");
sc.close();
}
}
Results:
1.
Input:
Enter a number:
3
Enter no of iterations:
1
Output:
Program Started AT : Sun May 15 13:40:45 IST 2016
Number is probably prime
Program Ended AT : Sun May 15 13:40:45 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 0 ms
Number of Iterations taken By the Program to Run : 2
1.
Input:
Enter a number:
4
Enter no of iterations:
1
Output:
Program Started AT : Sun May 15 13:40:45 IST 2016
Number is Composite
Program Ended AT : Sun May 15 13:40:45 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 0 ms
Number of Iterations taken By the Program to Run : 2
9
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

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 nave
approach and the KMP algorithm and compare their performances.
Objective of the Experiment :
To solve the string matching problem using Nave 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 :
Nave Algorithm
NAVE-STRING-MATCHER(T,P)
1 n=T.length
2 m=P.length
3 for s=0 to n-m
4 if P[1..m] == T[s+1..s+m]
5 print Pattern occurs with shift s
10
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


The prefix function,
Following pseudo code computes the prefix function, :
1 m length[p]
//p pattern to be matched
2 [1] 0
3 k0
4 for q 2 to m
5 do while k > 0 and p[k+1] != p[q]
6 do k [k]
7 If p[k+1] = p[q]
8 then k k +1
9 [q] k
10 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)
4q0
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 m
12
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:
Nave Algorithm
11
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


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();
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!");
}
}
12
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


}
KMP Algorithm
/**
** Java Program to implement Knuth Morris Pratt Algorithm
**/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
/** 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;
13
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


}
}
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++)
{
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:
Nave Algorithm
Input:
Enter text
Hello World
14
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


Enter pattern:
Wor
Output:
Program Started AT : Sun May 15 19:27:07 IST 2016
Matching found at 7
Program Ended AT : Sun May 15 19:27:07 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 0 ms
Number of Iterations taken By the Program to Run : 3
Input:
Enter text
Basavesvara Engineering College
Enter pattern:
college
Output:
Program Started AT : Sun May 15 19:29:56 IST 2016
Pattern not found
Program Ended AT : Sun May 15 19:29:56 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 0 ms
Number of Iterations taken By the Program to Run : 0
KMP Algorithm
Input:
Knuth Morris Pratt Test
Enter Text
Hello World
Enter Pattern
Wor
Output:
Program Started AT : Sun May 15 14:52:17 IST 2016
Pattern found at location: 7
Program Ended AT : Sun May 15 14:52:17 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 1 ms
Number of Iterations taken By the Program to Run : 13
Input:
15
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


Knuth Morris Pratt Test
Enter Text
Basavesvara Engineering College
Enter Pattern
college
Output:
Program Started AT : Sun May 15 15:00:24 IST 2016
Pattern not found
Program Ended AT : Sun May 15 15:00:24 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 0 ms
Number of Iterations taken By the Program to Run : 37
Comparison between KMP & Nave Algorithms
By seeing the output & performance in both the examples it is clear that Nave algorithm is most efficient
than KMP

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

Advanced Algorithms Laboratory (14SCS26)

Experiment No: 4
Title of the Experiment
Design, 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).
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

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

Advanced Algorithms Laboratory (14SCS26)


Algorithm:
FINITE-AUTOMATON-MATCHER(T, , m)
1 n
length[T]
2 q
0
3 for i
1 to n
4
do q
(q, T[i])
5
if q = m
6
then s
i - m
7
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)
{
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++)
{
18
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


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)
{
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 World
Enter pattern:
World
19
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)

Output:
Program Started AT : Sun May 15 15:07:26 IST 2016
Pattern found at 7
Program Ended AT : Sun May 15 15:07:26 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 1 ms
Number of Iterations taken By the Program to Run : 1567
Input:
Enter text:
Finite Automata
Enter pattern:
ataa
Output:
Program Started AT : Sun May 15 15:09:20 IST 2016
Pattern not found
Program Ended AT : Sun May 15 15:09:20 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 1 ms
Number of Iterations taken By the Program to Run : 1301

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

Advanced Algorithms Laboratory (14SCS26)

Experiment No: 5
Title of the Experiment
Design, 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.
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 alphabet
q: A prime number
h: d^(m-1)
21
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)

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)
{
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++)
22
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


{
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)
{
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();
23
Dept of Computer Science & Engineering, Basaveshwar Engineering College,
Bagalkot

Advanced Algorithms Laboratory (14SCS26)


}
}
Input:
Enter text:
Hello World
Enter pattern:
Wor
Enter base:
2
Enter prime number:
3
Output:
Program Started AT : Sun May 15 15:14:49 IST 2016
Pattern found at :7
Program Ended AT : Sun May 15 15:14:49 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 1 ms
Number of Iterations taken By the Program to Run : 20
Input:
Enter text:
Hello Worlds
Enter pattern:
Hello Worldn
Enter base:
2
Enter prime number:
3
Output:
Program Started AT : Sun May 15 15:14:49 IST 2016
Pattern Not found
Program Ended AT : Sun May 15 15:14:49 IST 2016
Performance Parameters:
Time Taken By the Program to Run : 1 ms
Number of Iterations taken By the Program to Run : 24

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

Advanced Algorithms Laboratory (14SCS26)

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

También podría gustarte