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

67 lines
1.3 KiB
Text
Raw Permalink Normal View History

2019-09-12 10:33:56 -07:00
import system'text;
import system'routines;
import extensions;
import extensions'text;
2018-06-22 20:57:24 +00:00
singleton compressor
{
2019-09-12 10:33:56 -07:00
string compress(string s)
{
auto tb := new TextBuilder();
int count := 0;
char current := s[0];
s.forEach:(ch)
{
2018-06-22 20:57:24 +00:00
if (ch == current)
2019-09-12 10:33:56 -07:00
{
2018-06-22 20:57:24 +00:00
count += 1
2019-09-12 10:33:56 -07:00
}
else
{
tb.writeFormatted("{0}{1}",count,current);
count := 1;
2018-06-22 20:57:24 +00:00
current := ch
2019-09-12 10:33:56 -07:00
}
};
2018-06-22 20:57:24 +00:00
2019-09-12 10:33:56 -07:00
tb.writeFormatted("{0}{1}",count,current);
2018-06-22 20:57:24 +00:00
^ tb
2019-09-12 10:33:56 -07:00
}
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)
}
};
2018-06-22 20:57:24 +00:00
^ tb
2019-09-12 10:33:56 -07:00
}
2018-06-22 20:57:24 +00:00
}
2019-09-12 10:33:56 -07:00
public program()
{
var s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
2018-06-22 20:57:24 +00:00
2019-09-12 10:33:56 -07:00
s := compressor.compress(s);
console.printLine(s);
2018-06-22 20:57:24 +00:00
2019-09-12 10:33:56 -07:00
s := compressor.decompress(s);
console.printLine(s)
}