Search code examples
algorithmlanguage-agnosticpseudocodelevenshtein-distance

Negative array index in a pseudocode


Consider this sample of a pseudocode for Levenshtein Distance:

function Leven_dyn(S1[1..m], S2[1..n], m, n);
var D[0..m, 0..n];
begin
  for i := 0 to m do
    D[i, 0] := i;
  end for
  for j := 0 to n do
    D[0, j] := j;
  end for
  for i := 0 to m do
    for j := 0 to n do
      a := D[i - 1, j] + 1;    // here accessing negative index
      b := D[i, j - 1] + 1;    // and here
      c := D[i - 1, j - 1];    // and here
      if S1[i] != S2[j] then
        c := c + 1;
      end if
      if min(a, b, c) = c then
        D[i, j] := c;
      else if min(a, b, c) = a then
        D[i, j] := a;
      else
        D[i, j] := b;
      end if
    end for
  end for
  return D
end

My first thought was that it's trying to access negative array's indexes, and I suppose that'd not be intentional behaviour.

Is the pseudocode plain wrong and the nested for loops should start from 1?

Or perhaps negative indexes in a pseudocode are somehow treated differently (for example ignored or something) than in normal language-dependant code, and thus that pseudocode would be good?


Solution

  • In general: The index constrains of most programming language should not need to apply also to pseudocode (even if most pseudocode do not use negative indexes).

    But in this case I think the nested loops should start with 1.

    The code is a dynamic programming implementation to calculate the Levenshtein Distance

    The first 2 loops initialize the upper and left border of the matrix. and the nested loops fill inner part of the matrix.

    You can find plenty of implemenattions of this pdeudocode. Eg. https://en.wikipedia.org/wiki/Levenshtein_distance