Run-length encoding: Difference between revisions

Updated D entry
(Added COBOL example. Corrected PL/I and R lang tags. Capitalised REXX section headers. Moved Befunge section to correct position.)
(Updated D entry)
Line 951:
 
// Similar to the 'look and say' function.
string encode(in string input) pure /*nothrow*/ {
if (input.empty) return input;
return input;
char last = input[$ - 1];
string output;
int count;
 
foreach_reverse (immutable c; input) {
if (c == last) {
count++;
} else {
output = text(count).text ~ last ~ output;
count = 1;
last = c;
Line 967 ⟶ 968:
}
 
return text(count).text ~ last ~ output;
}
 
string decode(in string input) pure {
string i, result;
 
foreach (immutable c; input)
switch (c) {
case '0': .. case '9':
Line 982 ⟶ 983:
throw new Exception("Can not repeat a letter " ~
"without a number of repetitions");
result ~= replicate([c], .replicate(i.to!int(i));
i.length = 0;
break;
default:
throw new Exception("'" ~ c ~ "' is not alphanumeric");
"' is not alphanumeric");
}
 
Line 997:
"WWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
writeln("Input: ", txt);
immutable encoded = encode(txt).encode;
writeln("Encoded: ", encoded);
assert(txt == decode(encoded).decode);
}</lang>
{{out}}
<pre>Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Encoded: 12W1B12W3B24W1B14W</pre>
 
===UTF String Version===
D's native string is utf-encoded. This version works for utf string, and uses a [[Variable-length_quantity|Variable-length Quantity]] [[Variable-length_quantity#D|module]].