0

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?

weno
  • 804
  • 8
  • 17
  • 2
    I personally would prefer recursive implementation of Levenshtein distance, but I think you're right - both loops should start from 1. The m and n are lengths of S1 and S2 accordingly, and hence they should iterate either from 0 to m-1, and 0 to n-1, or 1 to m and 1 to n. – Grzegorz Skibinski Sep 03 '19 at 12:36
  • Waht is the source of this pseudocode? In general I would say pseudocode is allowed to use negativ array-indexes. The index constrains of most programming language should not need to appply also for pseudocode. – MrSmith42 Sep 03 '19 at 12:39
  • @MrSmith42 It's from my university's algorithms and data structures course. – weno Sep 03 '19 at 12:55

1 Answers1

1

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

MrSmith42
  • 9,961
  • 6
  • 38
  • 49