RosettaCodeData/Task/Run-length-encoding/Elena/run-length-encoding.elena

67 lines
1.3 KiB
Plaintext

import system'text;
import system'routines;
import extensions;
import extensions'text;
singleton compressor
{
string compress(string s)
{
auto tb := new TextBuilder();
int count := 0;
char current := s[0];
s.forEach::(ch)
{
if (ch == current)
{
count += 1
}
else
{
tb.writeFormatted("{0}{1}",count,current);
count := 1;
current := ch
}
};
tb.writeFormatted("{0}{1}",count,current);
^ tb
}
string decompress(string s)
{
auto tb := new TextBuilder();
char current := $0;
var a := new StringWriter();
s.forEach::(ch)
{
current := ch;
if (current.isDigit())
{
a.append(ch)
}
else
{
int count := a.toInt();
a.clear();
tb.fill(current,count)
}
};
^ tb
}
}
public program()
{
var s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
s := compressor.compress(s);
console.printLine(s);
s := compressor.decompress(s);
console.printLine(s)
}