Time for an 2014 update…

This commit is contained in:
Ingy döt Net 2014-01-17 05:32:22 +00:00
parent 372c577f83
commit 09687c4926
2520 changed files with 34227 additions and 7318 deletions

View file

@ -1,29 +1,30 @@
import std.stdio, std.array, std.conv;
// Similar to the 'look and say' function.
string encode(in string input) {
if (input.empty) return input;
string encode(in string input) pure /*nothrow*/ {
if (input.empty)
return input;
char last = input[$ - 1];
string output;
int count;
foreach_reverse (c; input) {
foreach_reverse (immutable c; input) {
if (c == last) {
count++;
} else {
output = text(count) ~ last ~ output;
output = count.text ~ last ~ output;
count = 1;
last = c;
}
}
return text(count) ~ last ~ output;
return count.text ~ last ~ output;
}
string decode(in string input) {
string decode(in string input) pure {
string i, result;
foreach (c; input)
foreach (immutable c; input)
switch (c) {
case '0': .. case '9':
i ~= c;
@ -32,12 +33,11 @@ string decode(in string input) {
if (i.empty)
throw new Exception("Can not repeat a letter " ~
"without a number of repetitions");
result ~= replicate([c], to!int(i));
result ~= [c].replicate(i.to!int);
i.length = 0;
break;
default:
throw new Exception("'" ~ c ~
"' is not alphanumeric");
throw new Exception("'" ~ c ~ "' is not alphanumeric");
}
return result;
@ -47,7 +47,7 @@ void main() {
immutable txt = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWW" ~
"WWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
writeln("Input: ", txt);
immutable encoded = encode(txt);
immutable encoded = txt.encode;
writeln("Encoded: ", encoded);
assert(txt == decode(encoded));
assert(txt == encoded.decode);
}