How to resolve the algorithm Run-length encoding step by step in the Picat programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Run-length encoding step by step in the Picat programming language

Table of Contents

Problem Statement

Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it.

Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Run-length encoding step by step in the Picat programming language

Source code in the picat programming language

rle(S) = RLE => 
  RLE = "",
  Char = S[1],
  I = 2,
  Count = 1,
  while (I <= S.len)
    if Char == S[I] then
      Count := Count + 1
    else 
      RLE := RLE ++ Count.to_string() ++ Char.to_string(),
      Count := 1,
      Char := S[I]
    end,
    I := I + 1
  end,
  RLE := RLE ++ Count.to_string() ++ Char.to_string().

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('').

rle3(S) = RLE =>
  rle3(S.tail(),S[1],1,[],RLE).

rle3([],LastChar,Count,RLE1,RLE) =>
  RLE = (RLE1 ++ [Count.to_string(),LastChar.to_string()]).join('').

rle3([C|T],LastChar,Count,RLE1,RLE) =>
  C == LastChar ->
    rle3(T,C,Count+1,RLE1,RLE)
  ;
    rle3(T,C,1,RLE1++[Count.to_string()++LastChar.to_string()],RLE).

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.

go2 =>
  _ = random2(),
  Alpha = "AB",
  Len2 = Alpha.len,
  _ = random2(),
  S = [Alpha[random(1,Len2)] : _ in 1..30_000],
  if S.len < 200 then println(s=S) end ,
  println("rle/1:"),
  time(_=rle(S)),
  println("rle2/1:"),
  time(_=rle2(S)),
  println("rle3/1:"),
  time(_=rle3(S)),
  nl.

  

You may also check:How to resolve the algorithm Y combinator step by step in the E programming language
You may also check:How to resolve the algorithm Disarium numbers step by step in the Delphi programming language
You may also check:How to resolve the algorithm Sylvester's sequence step by step in the AWK programming language
You may also check:How to resolve the algorithm Combinations step by step in the jq programming language
You may also check:How to resolve the algorithm Musical scale step by step in the Clojure programming language