-3

Can someone give me a source code for a function - Rabin Karp algorithm - in pascal (free pascal version)?

  • No. Sorry. Stack Overflow is not a *"give me teh codez"* service... However, we could help you with a specific problem with your implementation attempt. – TLama May 06 '15 at 09:41
  • ok i just wanted to ask because i could not find it anywhere for pascal. – Djole R May 06 '15 at 10:13

1 Answers1

0

It's easy to found a function for the GNU Pascal

adapted to FPC:

program Project1;

function search (const pat: string; const  Text: string) : integer;
const
  b = 131;
var
  hpat,
  htext,
  Bm,
  j,
  m,
  n     : integer;
  found : Boolean;
begin
  found := False;
  result := 0;
  m := length (pat);
  if m = 0 then
  begin
    result := 1;
    found := true
  end;

  Bm := 1;
  hpat := 0;
  htext := 0;
  n := length (Text);
  if n >= m then
    {*** preprocessing ***}
    for j := 1 to m do
    begin
      Bm := Bm * b;
      hpat := hpat * b + ord (pat[j]);
      htext := htext * b + ord (Text[j])
    end;

  j := m;
  {*** search ***}
  while not found do
  begin
    if (hpat = htext) and (pat = Copy (Text, j - m + 1, m)) then
    begin
      result := j - m;
      found := true
    end;
    if j < n then
    begin
      j := j + 1;
      htext := htext * b - ord (Text[j - m]) * Bm + ord (Text[j])
    end
    else
      found := true;
  end
end;

begin
  writeln(Search('abcde', '0123456abcde'));
  writeln(Search('abcde', '012345678abcde'));
  writeln(Search('abcde', '0123456785785758'));
  readln;
end.

The only difference is that the function substr() is replaced with Copy().

Abstract type
  • 1,901
  • 2
  • 15
  • 26