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

67 lines
1.3 KiB
Text
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
import system'text;
import system'routines;
import extensions;
import extensions'text;
2026-02-01 16:33:20 -08:00
singleton Compressor
2023-07-01 11:58:00 -04:00
{
string compress(string s)
{
auto tb := new TextBuilder();
int count := 0;
char current := s[0];
2024-03-06 22:25:12 -08:00
s.forEach::(ch)
2023-07-01 11:58:00 -04:00
{
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();
2024-03-06 22:25:12 -08:00
s.forEach::(ch)
2023-07-01 11:58:00 -04:00
{
current := ch;
if (current.isDigit())
{
a.append(ch)
}
else
{
int count := a.toInt();
a.clear();
tb.fill(current,count)
}
};
^ tb
}
}
2026-02-01 16:33:20 -08:00
public Program()
2023-07-01 11:58:00 -04:00
{
var s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
2026-02-01 16:33:20 -08:00
s := Compressor.compress(s);
Console.printLine(s);
2023-07-01 11:58:00 -04:00
2026-02-01 16:33:20 -08:00
s := Compressor.decompress(s);
Console.printLine(s)
2023-07-01 11:58:00 -04:00
}