August 29, 2007
As an exercise, my take at this problem (D 1.X):

import std.stdio,, 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",

  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.)

Top | Discussion index | About this forum | D home