次の方法で共有


Ambiguous Morse Solver

Decoding Morse Code when there are character delimiters is fairly trivial. When you don’t know where each character begins in the string, it becomes a little more difficult. You can solve it with recursion without too much trouble, but you can also solve it with a single line of LINQ! (Well, you also need a Dictionary<string, string> of Morse to English.)

return from item in MorseToLetterDict
        where s.StartsWith(item.Key)
        select new {
            Value = item.Value,
            Prefix = prefix,
            Children = YieldTopLevel(prefix + item.Value, morsePrefix + item.Key, s.Substring(item.Key.Length))
        };

It’s so elegant! Technically this just builds your tree so you’ll have to flatten it to print out all the results, but this single line accomplishes the hard part of the problem.

The first time I saw this code was when DaveM wrote it, but that got lost over time. So this time when I rewrote it, I decided to share it with the world and archive it. Thanks Dave!