One Fold Away from Clarity
The first person to try my accordion guide paused at the third panel. I had drawn the wire loop from above; they were still holding the puzzle as shown from the side. They turned the whole puzzle over, then spent a while looking for a move that wasn’t there.
For the next draft, I gave each panel a letter representing its viewpoint. The intended sequence was ABCD; the tested guide effectively read ABD, missing the transition into viewpoint C. How different are those sequences? Levenshtein distance answers with the smallest number of single-item insertions, deletions and substitutions needed to turn one into the other. Here, the answer is one: insert C.
Swift keeps a row of distances as it works across each character of the first sequence:
func distance(_ a: String, _ b: String) -> Int {
let right = Array(b)
var row = Array(0...right.count)
for (i, x) in a.enumerated() {
var next = [i + 1]
for (j, y) in right.enumerated() {
next.append(min(row[j + 1] + 1, next[j] + 1,
row[j] + (x == y ? 0 : 1)))
}
row = next
}
return row[right.count]
}
print(distance("ABCD", "ABD")) // 1
Each cell considers three possibilities: delete the current item, insert one, or match or substitute it. The previous row supplies two of those possibilities; the current row supplies the third. Starting with 0, 1, 2, ... accounts for building a sequence from nothing.
Perl follows the same trail, with arrays standing in for the rows:
use strict;
use warnings;
my @a = split //, 'ABCD';
my @b = split //, 'ABD';
my @row = (0 .. @b);
for my $i (0 .. $#a) {
my @next = ($i + 1);
for my $j (0 .. $#b) {
my @cost = ($row[$j + 1] + 1, $next[$j] + 1,
$row[$j] + ($a[$i] ne $b[$j]));
$next[$j + 1] = (sort { $a <=> $b } @cost)[0];
}
@row = @next;
}
print "$row[@b]\n"; # 1
The score is a useful flag, not a verdict on whether a drawing is understandable. It treats every edit as equally costly, although a missing change of viewpoint may confuse a reader more than a repeated panel. Keeping just one previous row saves space, too, but these snippets report the distance without reconstructing the edits. For the guide, watching someone handle the wire still tells me where the extra drawing belongs.