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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Run-length encoding step by step in the zkl 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 zkl programming language

Source code in the zkl programming language

const MAX_LEN=250, MIN_LEN=3;
fcn compress(text){ // !empty byte/text stream -->Data (byte stream)
   sink:=Data(); cnt:=Ref(0);
   write:='wrap(c,n){ // helper function
      while(n>MAX_LEN){ 
         sink.write(1); sink.write(MAX_LEN); sink.write(c); 
	 n-=MAX_LEN;
      }
      if(n>MIN_LEN){ sink.write(1); sink.write(n); sink.write(c); }
      else { do(n) { sink.write(c); } }
   };
   text.reduce('wrap(a,b){
      if(a==b) cnt.inc();
      else{ write(a,cnt.value); cnt.set(1); }
      b
   },text[0]) : write(_,cnt.value);
   sink;
}

fcn inflate(data){  //-->String
   data.howza(3).pump(String,
      fcn(c){ // if c==1, read n,c2 and expand, else write c
         if(c=="\x01") return(Void.Read,2) else return(Void.Write,c) },
      fcn(_,n,c){ c*n.toAsc() })
}

text:="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
d:=compress(text);
d.bytes().println();
println(text.len()," bytes --> ",d.len()," bytes");
println(text==inflate(d));

  

You may also check:How to resolve the algorithm Wireworld step by step in the Wren programming language
You may also check:How to resolve the algorithm Forward difference step by step in the Objeck programming language
You may also check:How to resolve the algorithm Tokenize a string step by step in the Phixmonti programming language
You may also check:How to resolve the algorithm Flow-control structures step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm Base64 decode data step by step in the jq programming language