Created
January 14, 2024 17:44
-
-
Save ssvb/abe821b3cdba7fcb7f3c3cecde864153 to your computer and use it in GitHub Desktop.
The initial simple Dlang solution for https://flownet.com/ron/papers/lisp-java/instructions.html and https://github.com/renatoathaydes/prechelt-phone-number-encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/+dub.sdl:+/ | |
// Siarhei Siamashka - Programming Challange from Erann Gat: | |
// http://www.flownet.com/ron/papers/lisp-java/ | |
// This work is marked with CC0 1.0. To view a copy of this license, visit | |
// http://creativecommons.org/publicdomain/zero/1.0 | |
@safe: | |
import std.stdio, std.file, std.conv, std.ascii, std.algorithm, std.string; | |
immutable letter2digit = (){ | |
char[256] tmp; | |
tmp[] = 0; | |
auto letter2digit_txt = | |
"E | J N Q | R W X | D S Y | F T | A M | C I V | B K U | L O P | G H Z | |
e | j n q | r w x | d s y | f t | a m | c i v | b k u | l o p | g h z | |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9"; | |
char curdigit = '0'; | |
foreach (ch; letter2digit_txt) { | |
if (ch == '|') | |
curdigit++; | |
else if (ch == '\n') | |
curdigit = '0'; | |
else if (std.ascii.isAlpha(ch)) | |
tmp[ch] = curdigit; | |
} | |
return tmp; | |
}(); | |
void main(string[] argv) { | |
if (argv.length < 3) { | |
writefln!"Usage: %s [dictionary.txt] [input.txt]"(argv[0]); | |
return; | |
} | |
string dictionary_txt = readText(argv[1]).strip; | |
string[][string] num2word; | |
foreach (line; dictionary_txt.splitter('\n')) { | |
auto word = line.strip; | |
auto num = word.map!(ch => letter2digit[ch]).filter!"a != 0".to!string; | |
num2word[num] ~= word; | |
} | |
void solve(char[] prefix, int already_skipped, string phone) { | |
if (phone.empty) { | |
writeln(prefix); | |
return; | |
} | |
bool found_match = false; | |
foreach (i; 1 .. phone.length + 1) { | |
auto words = phone[0 .. i] in num2word; | |
if (words) { | |
found_match = true; | |
foreach (word; *words) | |
solve(prefix ~ " " ~ word, 0, phone[i .. $]); | |
} | |
} | |
if (!found_match && already_skipped == 0) | |
solve(prefix ~ " " ~ phone[0 .. 1], 1, phone[1 .. $]); | |
} | |
() @trusted { // workaround https://issues.dlang.org/show_bug.cgi?id=18110 | |
foreach (line; File(argv[2]).byLine) { | |
auto phone = line.filter!"a >= '0' && a <= '9'".to!string; | |
solve(line.strip ~ ":", 0, phone); | |
} | |
}(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment