by OskarS · 6y ago · 0 comments
letter(a, X) :- string_to_list("._", X).
letter(b, X) :- string_to_list("_...", X).
/* rest ommitted for brevity */
letter(z, X) :- string_to_list("__..", X).
morse([], []).
morse(Morse, [Letter|Rest]) :-
letter(Letter, Head),
append(Head, Tail, Morse),
morse(Tail, Rest).
Prolog is obviously excellent for this kind of thing since the backtracking comes built in, but it's not massively more complicated in other languages.For "_.._", it gives you the following answers (I added some line-breaks):
?- string_to_list("_.._", L),
findall(English, morse(L, English), Answers).
L = [95, 46, 46, 95],
Answers = [[d, t],
[n, a],
[n, e, t],
[t, e, a],
[t, e, e, t],
[t, i, t],
[t, u],
[x]].
I wasn't saying that it's not a good little problem. It's a lovely little problem, which you solve with recursive back-tracking! I wouldn't say it's a "trick question" though, it's just a regular programming challenge.EDIT: Oh, I see what you're saying, do you mean "It's a trick question because there isn't necessarily just one answer"?
If so, then I misunderstood, I figured the challenge was "find all valid interpretations" of a certain morse code string. The fact that there could be more than one seemed fairly obvious to me.
edit: oooh and use beam search to limit the output size/time
There will be lots of ways to split any given prefix into letters. But all of them leave the same suffix. You don't need to repeat the analysis of the suffix.
You could avoid repeating the analysis by memoising the result. But when you're memoising results from leaves of a search tree, that's a hint that you're close to a dynamic programming approach.
I guess you could instead return some kind of fancy "prefix DAG" containing all possible strings, and that would be faster. But then you're just making the caller walk that tree instead of you doing it yourself, so you're really just shuffling the runtime around, not really saving much.
However, if the answer is "count the solutions", then yeah, memoizing would speed it up MASSIVELY. That's a good little Project Euler style problem, actually (though not a terribly tricky one), because you could make the input large enough that naive recursive descent wouldn't work. I haven't quite thought through what going full-on DP and turning the recursion upside down would do, but I assume it would work just fine.
But given that the number of possible solutions is a massive O(2^n) (probably, anyway), that puts a floor on the runtime you can't algorithm your way out of. Might as well go with the cheap recursive descent. I think, anyway :)