How to resolve the algorithm Move-to-front algorithm step by step in the Picat programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Move-to-front algorithm step by step in the Picat 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 Picat programming language
Source code in the picat programming language
import util.
go =>
Strings = ["broood", "bananaaa", "hiphophiphop"],
foreach(String in Strings)
check(String)
end,
nl.
% adjustments to 1-based index
encode(String) = [Pos,Table] =>
Table = "abcdefghijklmnopqrstuvwxyz",
Pos = [],
Len = String.length,
foreach({C,I} in zip(String,1..Len))
Pos := Pos ++ [find_first_of(Table,C)-1],
if Len > I then
Table := [C] ++ delete(Table,C)
end
end.
decode(Pos) = String =>
Table = "abcdefghijklmnopqrstuvwxyz",
String = [],
foreach(P in Pos)
C = Table[P+1],
Table := [C] ++ delete(Table,C),
String := String ++ [C]
end.
% Check the result
check(String) =>
[Pos,Table] = encode(String),
String2 = decode(Pos),
if length(String) < 100 then
println(pos=Pos),
println(table=Table),
println(string2=String2)
else
printf("String is too long to print (%d chars)\n", length(String))
end,
println(cond(String != String2, "not ", "") ++ "same"),
nl.
You may also check:How to resolve the algorithm Happy numbers step by step in the J programming language
You may also check:How to resolve the algorithm Strip a set of characters from a string step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Partition function P step by step in the Racket programming language
You may also check:How to resolve the algorithm Levenshtein distance step by step in the Forth programming language
You may also check:How to resolve the algorithm Four is magic step by step in the AppleScript programming language