Run-length encoding
editable example
Click the pencil to open this in an editor, change it, and run it in your browser. The same solution is posted on Rosetta Code.
ghul
use IO.Std.write_line
use Ghul.Pipes
encode(text: string) -> string is
let runs = System.Text.StringBuilder()
let at mut = 0
while at < text.length do
let start = at
while at < text.length /\ text[at] == text[start] do
at = at + 1
od
runs.append(at - start)
runs.append(text[start])
od
return runs.to_string()
si
decode(encoded: string) -> string is
let text = System.Text.StringBuilder()
let at mut = 0
while at < encoded.length do
let start = at
while char.is_digit(encoded[at]) do
at = at + 1
od
let count = int.parse(encoded.substring(start, at - start))
text.append(encoded[at], count)
at = at + 1
od
return text.to_string()
si
let input =
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWW"
"WWWWWWWWWWWWBWWWWWWWWWWWWWW"
let encoded = encode(input)
write_line("input: {input}")
write_line("encoded: {encoded}")
write_line("decoded: {decode(encoded)}")
write_line("round trip restores the input: {decode(encoded) =~ input}")