Run-length encoding: Difference between revisions

Line 686:
<lang csharp>using System.Collections.Generic;
using System.Linq;
using static System.Linq.EnumerableEx;
using static System.Console;
 
Line 692 ⟶ 693:
static class Program
{
public static string Encode(string input) => input
.Buffer(2, 1).Select(p => (f: p[0], s: p.Count > 1 ? p[1] : p[0])).SkipLast(1)
{
.Scan((val: '\0', key: 0), (scn, fs) => (val: fs.s, key: fs.f == fs.s ? scn.key : scn.key + 1))
var adj = 0;
return input.ZipPrepend(input.Skip(1).Concat(newval: charinput[0], {key: default }0)),
.GroupBy(kvp => kvp.key, (f_, svals) => (val: f, key: svals.EqualsSelect(default)t ||=> ft.Equals(s) ? adj : adj++val))
.GroupBySelect(t v=> t$"{v.key, Count(_, grp) => grp}{v.SelectFirst(t => t.val)}")
.SelectStringConcat(a => (key: a.Count(), chr: a.First()));
.Select(c => c.key == 1 ? $"{c.chr}" : $"{c.key}{c.chr}")
.StringConcat();
}
 
public static string Decode(string input) => input
.Buffer(2, 1).Select(p => (f: p[0], s: p.Count > 1 ? p[1] : p[0])).SkipLast(1)
{
.Scan((val: '\0', key: 0), (scn, pair) => (val: pair.s, key: char.IsDigit(pair.s) && char.IsLetter(pair.f) ? scn.key + 1 : scn.key))
int IntParse(IEnumerable<char> p) => int.Parse(string.Concat(p.Reverse().Skip(1).Reverse()));
var adj.Prepend((val: =input[0], key: 0;))
.GroupBy(t => t.key, (_, grp) => grp.Select(c => c.val))
return input
.Select(fp => (val:new fstring(p.Last(), key: charint.IsDigitParse(fstring.Concat(p.SkipLast(1))) ? adj : adj++))
.GroupByStringConcat(t => t.key,(_,grp)=>grp.Select(c=>c.val));
 
.Select(p => p.Count() == 1 ? $"{p.First()}" : new string(p.Last(), IntParse(p)))
private static string StringConcat(this IEnumerable<string> seq) => string.Concat(seq);
.StringConcat();
}
 
private static string StringConcat(this IEnumerable<string> seq) => string.Concat(seq);
 
public static void Main(string[] args)
Line 722 ⟶ 718:
 
WriteLine($"raw = {raw}");
WriteLine($"encoded = {encoded}");
WriteLine($"Encode(raw) = encoded = {Encode(raw)}");
WriteLine($"Decode(encode) = {Decode(encoded)}");
WriteLine($"Decode(Encode(raw)) = {Decode(Encode(raw)) == raw}");
ReadLine();
}
}
}</lang>
Output:
<pre>raw = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
encoded = 12W1B12W3B24W1B14W
Encode(raw) = encoded = 12W1B12W3B24W1B14W
Decode(encode) = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Decode(Encode(raw)) = True
</pre>
 
Many solutions do not follow the suggested output guideline in the challenge (not helped by its wording), instead producing a list of tuples or equivalent. This is much simpler (especially for decode) and the following provides an equivalent of those (IMHO deficient) solutions, to make comparisons easier.