Run-length encoding: Difference between revisions
Content deleted Content added
Updated two of the four D versions |
|||
Line 724:
=={{header|D}}==
<lang d>import std.stdio;▼
<lang d>import std.
void main() {▼
char[]rle = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";▼
char[]encoded = encode(rle);▼
char[]decoded = decode(encoded);▼
}▼
//
char last = input[$ - 1];
int count
foreach_reverse (i; input) {
if (i == last) {
count++;
} else {
output =
count = 1;
last = i;
}
}
return text(count) ~ last ~ output;
}
foreach (letter; input) {
if (letter <= 'Z' && letter >= 'A') {
// this is the letter to be repeated
if (i.empty)
result ~= replicate([letter], to!int(i));
i.length = 0;
} else if (letter <= '9' && letter >= '0') {
// this is a digit to mark the number of repetitions
i ~= letter;
} else {
throw new Exception("'" ~ letter ~ "' is not
}
}
return
▲}
▲void main() {
writeln("Input: ", txt);
writeln("Encoded: ", encoded);
}</lang>
===Short Functional Version===▼
▲<lang d>import std.stdio, std.algorithm, std.conv, std.array;
alias group encode;▼
▲===Utf String Version===
string decode(Range)(Range r) {▼
}▼
void main() {▼
auto s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";▼
assert(decode(encode(s)) == s);▼
}</lang>▼
===UTF String Version===
D's native string is utf-encoded. This version work for utf string. This code use a [[Variable-length_quantity|Variable-length Quantity]] [[Variable-length_quantity#D|module]].
Line 866 ⟶ 883:
'''NOTE :''' some characters in this section use Chinese font.
===
{{trans|Python}} regular expression version
Line 888 ⟶ 905:
},
"g") ;
▲}</lang>
▲===Short Functional Version===
▲alias group encode;
▲string decode(Range)(Range r) {
▲ return array(map!((t){ return repeat(""~cast(char)t[0], t[1]); })(r)).join();
▲}
▲void main() {
▲ auto s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
▲ assert(decode(encode(s)) == s);
}</lang>
|