How to resolve the algorithm Move-to-front algorithm step by step in the Raku programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Move-to-front algorithm step by step in the Raku programming language

Table of Contents

Problem Statement

Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms.

Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   a-to-z

Decoding the indices back to the original symbol order:

The strings are:

(Note the misspellings in the above strings.)

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Move-to-front algorithm step by step in the Raku programming language

Source code in the raku programming language

sub encode ( Str $word ) {
    my @sym = 'a' .. 'z';
    gather for $word.comb -> $c {
	die "Symbol '$c' not found in @sym" if $c eq @sym.none;
        @sym[0 .. take (@sym ... $c).end] .= rotate(-1);
    }
}
 
sub decode ( @enc ) {
    my @sym = 'a' .. 'z';
    [~] gather for @enc -> $pos {
        take @sym[$pos];
        @sym[0..$pos] .= rotate(-1);
    }
}
 
use Test;
plan 3;
for  -> $word {
    my $enc = encode($word);
    my $dec = decode($enc);
    is $word, $dec, "$word.fmt('%-12s') ($enc[])";
}


  

You may also check:How to resolve the algorithm Digital root step by step in the Clojure programming language
You may also check:How to resolve the algorithm Filter step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm JSON step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Array concatenation step by step in the Phixmonti programming language
You may also check:How to resolve the algorithm Quaternion type step by step in the Delphi programming language