Lisp-Java-D
bearophile
bearophileHUGS at lycos.com
Wed Aug 29 00:22:25 PDT 2007
As an exercise, my take at this problem (D 1.X):
http://www.digitalmars.com/d/lisp-java-d.html
import std.stdio, std.stream, std.string, std.ctype;
void traduct(string n, string digits, int start, string[] words, string[][string] gdict) {
if (start >= digits.length)
writefln(n, ": ", words.join(" "));
else {
auto found_word = false;
for(auto i = start; i < digits.length; i++)
if (digits[start .. i+1] in gdict) {
found_word = true;
foreach(hit; gdict[digits[start .. i+1]])
traduct(n, digits, i+1, words ~ [hit], gdict);
}
if (!found_word && (!words || (words && !std.ctype.isdigit(words[words.length-1][0]))))
traduct(n, digits, start+1, words ~ [digits[start..start+1]], gdict);
}
}
void main() {
auto gtable = maketrans("ejnqrwxdsyftamcivbkulopghzEJNQRWXDSYFTAMCIVBKULOPGHZ",
"0111222333445566677788899901112223334455666777888999");
string[][string] gdict;
foreach(string w; new BufferedFile("dictionary.txt"))
gdict[w.translate(gtable, "\"")] ~= w.dup;
foreach(string n; new BufferedFile("input.txt"))
traduct(n, n.removechars("/-"), 0, [], gdict);
}
It's faster than my Python version and it shows that D code can be positively coincise too.
(I have found ways to speed this D code up, using a bit lower-level coding, disabling the GC in the beginning, etc, but I think this is a good speed/linecount compromise, and it looks readable enough.)
Bye,
bearophile
More information about the Digitalmars-d
mailing list