Anonymous user
Run-length encoding: Difference between revisions
→Linq
m (→Linq) |
(→Linq) |
||
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))
.GroupBy(kvp => kvp.key, (
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))
.GroupBy(t => t.key, (_, grp) => grp.Select(c => c.val))
▲ 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.
|