Run-length encoding: Difference between revisions
→{{header|Picat}}: Split into subsections
(→{{header|Picat}}: Split into subsections) |
|||
Line 4,159:
=={{header|Picat}}==
===While loop===
<lang Picat>rle(S) = RLE => ▼
* using positions of different chars: rle2/1▼
Encode and decode (only using rle3/1):▼
<lang Picat>▼
S = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWWA",▼
println(S),▼
RLE = rle3(S),▼
println(rle=RLE),▼
D = rl_decode(RLE),▼
println(D),▼
if D == S then▼
println(ok)▼
else▼
println(not_ok)▼
end,▼
nl.▼
▲% While loop. Quite slow.
▲rle(S) = RLE =>
RLE = "",
Char = S[1],
Line 4,199 ⟶ 4,176:
I := I + 1
end,
RLE := RLE ++ Count.to_string() ++ Char.to_string().</lang>
<lang Picat>rle2(S) = RLE =>▼
▲rle2(S) = RLE =>
Ix = [1] ++ [I : I in 2..S.len, S[I] != S[I-1]] ++ [S.len+1],
Diffs = diff(Ix),
RLE = [Diffs[I].to_string() ++ S[Ix[I]].to_string() : I in 1..Diffs.len].join('').</lang>
===Recursive approach===
<lang Picat>rle3(S) = RLE =>
rle3(S.tail(),S[1],1,[],RLE).
Line 4,222 ⟶ 4,198:
;
rle3(T,C,1,RLE1++[Count.to_string()++LastChar.to_string()],RLE).</lang>
===Test===
▲Encode and decode (only using <code>rle3/1</code>):
▲<lang Picat>go =>
▲ S = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWWA",
▲ println(S),
▲ RLE = rle3(S),
▲ println(rle=RLE),
▲ D = rl_decode(RLE),
▲ println(D),
▲ if D == S then
▲ println(ok)
▲ else
▲ println(not_ok)
▲ end,
▲ nl.</lang>
{{out}}
Line 4,227 ⟶ 4,219:
rle = 12W1B12W3B24W1B14W1A
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWWA
ok</pre>
===Benchmark on
A benchmark on a larger string (30_000) clearly shows that rle3/1 is the fastest.
<lang Picat>go2 =>
_ = random2(),
Alpha = "AB",
|