www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Lisp-Java-D

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

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

Aug 29 2007