wordladder - code improvement

dwdv dwdv at posteo.de
Fri Jan 31 11:06:18 UTC 2020


On 2020-01-31 09:44, mark via Digitalmars-d-learn wrote:
> I can't use the levenshtien distance because although it is a better solution, [...]

Nah, it isn't, sorry for the noise, should have slept before sending the message, was thinking of 
hamming distance:

auto a = "abcd";
auto b = "bcda";

auto hammingDistance(string a, string b) {
     return zip(a, b).count!(t => t[0] != t[1]);
}

levenshteinDistance(a, b).writeln; // => 2
hammingDistance(a, b).writeln;     // => 4

> main() [...] doesn't match the behaviour

There's also std.range.tee if you ever need to perform additional side-effects in a range pipeline, 
which restores the original dot printing:

write("Try ");
auto res = generate!(() => genLadder(words.dup, STEPS))
     .enumerate(1)
     .tee!(_ => write('.'), No.pipeOnPop) // No.pipeOnPop ensures we're not one dot short
     .find!(a => !a[1].empty)
     .front;
writeln(" ", res[0]);

> genLadder() [...] is so compact.

Thinking about it, you could even eliminate the prev variable all together when using ladder.back in 
compWords.

Regarding const correctness, this article and thread might contain useful information: 
https://forum.dlang.org/thread/2735451.YHZktzbKJo@lyonel

By the way, keep the documentation improvements coming, much appreciated!



More information about the Digitalmars-d-learn mailing list