RosettaCodeData/Task/Run-length-encoding/D/run-length-encoding-2.d

54 lines
1.4 KiB
D
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
import std.stdio, std.array, std.conv;
// Similar to the 'look and say' function.
2015-02-20 00:35:01 -05:00
string encode(in string input) pure nothrow @safe {
2014-01-17 05:32:22 +00:00
if (input.empty)
return input;
2013-04-10 23:57:08 -07:00
char last = input[$ - 1];
string output;
int count;
2014-01-17 05:32:22 +00:00
foreach_reverse (immutable c; input) {
2013-04-10 23:57:08 -07:00
if (c == last) {
count++;
} else {
2014-01-17 05:32:22 +00:00
output = count.text ~ last ~ output;
2013-04-10 23:57:08 -07:00
count = 1;
last = c;
}
}
2014-01-17 05:32:22 +00:00
return count.text ~ last ~ output;
2013-04-10 23:57:08 -07:00
}
2015-02-20 00:35:01 -05:00
string decode(in string input) pure /*@safe*/ {
2013-04-10 23:57:08 -07:00
string i, result;
2014-01-17 05:32:22 +00:00
foreach (immutable c; input)
2013-04-10 23:57:08 -07:00
switch (c) {
case '0': .. case '9':
i ~= c;
break;
case 'A': .. case 'Z':
if (i.empty)
throw new Exception("Can not repeat a letter " ~
"without a number of repetitions");
2014-01-17 05:32:22 +00:00
result ~= [c].replicate(i.to!int);
2013-04-10 23:57:08 -07:00
i.length = 0;
break;
default:
2014-01-17 05:32:22 +00:00
throw new Exception("'" ~ c ~ "' is not alphanumeric");
2013-04-10 23:57:08 -07:00
}
return result;
}
void main() {
immutable txt = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWW" ~
"WWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
writeln("Input: ", txt);
2014-01-17 05:32:22 +00:00
immutable encoded = txt.encode;
2013-04-10 23:57:08 -07:00
writeln("Encoded: ", encoded);
2014-01-17 05:32:22 +00:00
assert(txt == encoded.decode);
2013-04-10 23:57:08 -07:00
}