Move-to-front algorithm: Difference between revisions

Added Easylang
(add FreeBASIC)
(Added Easylang)
 
(8 intermediate revisions by 7 users not shown)
Line 112:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V symboltable = Array(‘a’..‘z’)
 
F move2front_encode(strng)
Line 137:
V decode = move2front_decode(encode)
print(‘which decodes back to #.’.format(decode))
assert(s == decode, ‘Whoops!’)</langsyntaxhighlight>
 
{{out}}
Line 144:
bananaaa encodes to [1, 1, 13, 1, 1, 1, 0, 0], which decodes back to bananaaa
hiphophiphop encodes to [7, 8, 15, 2, 15, 2, 2, 3, 2, 2, 3, 2], which decodes back to hiphophiphop
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE SYMBOL_TABLE_SIZE="26"
 
PROC InitSymbolTable(BYTE ARRAY table BYTE len)
BYTE i
 
FOR i=0 TO len-1
DO
table(i)=i+'a
OD
RETURN
 
BYTE FUNC Find(BYTE ARRAY table BYTE len,c)
BYTE i
 
FOR i=0 TO len-1
DO
IF table(i)=c THEN
RETURN (i)
FI
OD
Break()
RETURN (0)
 
PROC MoveToFront(BYTE ARRAY table BYTE len,pos)
BYTE sym
 
sym=table(pos)
WHILE pos>0
DO
table(pos)=table(pos-1)
pos==-1
OD
table(pos)=sym
RETURN
 
PROC Encode(CHAR ARRAY in BYTE ARRAY out BYTE POINTER outLen)
BYTE ARRAY table(SYMBOL_TABLE_SIZE)
BYTE i,pos
 
outLen^=0
InitSymbolTable(table,SYMBOL_TABLE_SIZE)
FOR i=1 TO in(0)
DO
pos=Find(table,SYMBOL_TABLE_SIZE,in(i))
out(outLen^)=pos
outLen^==+1
MoveToFront(table,SYMBOL_TABLE_SIZE,pos)
OD
RETURN
 
PROC Decode(BYTE ARRAY in BYTE inLen CHAR ARRAY out)
BYTE ARRAY table(SYMBOL_TABLE_SIZE)
BYTE i,pos,len
 
len=0
InitSymbolTable(table,SYMBOL_TABLE_SIZE)
FOR i=0 TO inLen-1
DO
pos=in(i)
len==+1
out(len)=table(pos)
MoveToFront(table,SYMBOL_TABLE_SIZE,pos)
OD
out(0)=len
RETURN
 
PROC Test(CHAR ARRAY s)
BYTE ARRAY encoded(255)
CHAR ARRAY decoded(256)
BYTE encodedLength,i
 
Print("Source: ")
PrintE(s)
 
Encode(s,encoded,@encodedLength)
Print("Encoded: ")
FOR i=0 TO encodedLength-1
DO
PrintB(encoded(i)) Put(32)
OD
PutE()
 
Decode(encoded,encodedLength,decoded)
Print("Decoded: ")
PrintE(decoded)
IF SCompare(s,decoded)=0 THEN
PrintE("Decoded is equal to the source.")
ELSE
PrintE("Decoded is different from the source!")
FI
PutE()
RETURN
 
PROC Main()
Test("broood")
Test("bananaaa")
Test("hiphophiphop")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Move-to-front_algorithm.png Screenshot from Atari 8-bit computer]
<pre>
Source: broood
Encoded: 1 17 15 0 0 5
Decoded: broood
Decoded is equal to the source.
 
Source: bananaaa
Encoded: 1 1 13 1 1 1 0 0
Decoded: bananaaa
Decoded is equal to the source.
 
Source: hiphophiphop
Encoded: 7 8 15 2 15 2 2 3 2 2 3 2
Decoded: hiphophiphop
Decoded is equal to the source.
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Move_To_Front is
Line 229 ⟶ 347:
Encode_Write_Check("bananaaa");
Encode_Write_Check("hiphophiphop");
end Move_To_Front;</langsyntaxhighlight>
 
{{out}}
Line 238 ⟶ 356:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">decode(list l)
{
integer c, e;
Line 278 ⟶ 396:
 
0;
}</langsyntaxhighlight>
{{out}}
<pre> 1 17 15 0 0 5: broood
Line 286 ⟶ 404:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># move the character at text pos to the front of text #
# note text pos is based from 0 #
PROC move to front = ( STRING text, INT text pos )STRING:
Line 422 ⟶ 540:
# ; test encode and decode( "zyxwvutsrqponmlkjihgfedcba" ) #
 
)</langsyntaxhighlight>
{{out}}
<pre>
Line 429 ⟶ 547:
hiphophiphop encodes to [ 7 8 15 2 15 2 2 3 2 2 3 2 ] which correctly decodes to "hiphophiphop"
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">
symbolTable: @`a`..`z`
 
encodeWord: function [s][
symt: new symbolTable
result: []
loop s 'c [
idx: index symt c
'result ++ idx
symt: (rotate symt\[0..idx] 1) ++ symt\[(idx+1)..dec size symt]
]
return result
]
 
decodeWord: function [s][
symt: new symbolTable
result: []
loop s 'idx [
'result ++ symt\[idx]
symt: (rotate symt\[0..idx] 1) ++ symt\[(idx+1)..dec size symt]
]
return join result
]
 
loop ["broood", "babanaaa", "hiphophiphop"] 'word [
encoded: encodeWord word
decoded: decodeWord encoded
print ["'"++word++"'" "encodes to" encoded "which correctly decodes to" "'"++decoded++"'"]
]</syntaxhighlight>
 
{{out}}
 
<pre>'broood' encodes to [1 17 15 0 0 5] which correctly decodes to 'broood'
'babanaaa' encodes to [1 1 1 1 13 1 0 0] which correctly decodes to 'babanaaa'
'hiphophiphop' encodes to [7 8 15 2 15 2 2 3 2 2 3 2] which correctly decodes to 'hiphophiphop'</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MTF_Encode(string){
str := "abcdefghijklmnopqrstuvwxyz"
loop, parse, string
Line 444 ⟶ 599:
return string
}
</syntaxhighlight>
</lang>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">testStrings = broood,bananaaa,hiphophiphop
loop, parse, testStrings, `,
Output .= A_LoopField "`t" MTF_Encode(A_LoopField) "`t" MTF_Decode(MTF_Encode(A_LoopField)) "`n"
MsgBox % Output
return</langsyntaxhighlight>
Outputs:<pre>broood 1,17,15,0,0,5 broood
bananaaa 1,1,13,1,1,1,0,0 bananaaa
Line 455 ⟶ 610:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat"> ( encode
= string symboltable
. !arg:(?string.?symboltable)
Line 500 ⟶ 655:
& test$(broood.!symboltable)
& test$(bananaaa.!symboltable)
& test$(hiphophiphop.!symboltable)</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include<stdio.h>
#include<stdlib.h>
#include<string.h>
Line 590 ⟶ 745:
}
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>broood : [1 17 15 0 0 5 ]
Line 600 ⟶ 755:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 674 ⟶ 829:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">
<lang Cpp>
#include <iostream>
#include <iterator>
Line 760 ⟶ 915:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 769 ⟶ 924:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(def lowercase (map char (range (int \a) (inc (int \z)))))
 
(defn move-to-front [x xs]
Line 789 ⟶ 944:
decoded (decode encoded lowercase)]
(println (format "%s encodes to %s which decodes back to %s."
word encoded decoded))))</langsyntaxhighlight>
 
{{Out}}
Line 799 ⟶ 954:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defconstant +lower+ (coerce "abcdefghijklmnopqrstuvwxyz" 'list))
 
(defun move-to-front (x xs)
Line 825 ⟶ 980:
(assert (string= word decoded))
(format T "~s encodes to ~a which decodes back to ~s.~%"
word encoded decoded)))</langsyntaxhighlight>
 
{{Out}}
Line 833 ⟶ 988:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.ascii, std.algorithm;
 
ptrdiff_t[] mtfEncoder(in string data) pure nothrow @safe
Line 881 ⟶ 1,036:
assert(word == decoded);
}
}</langsyntaxhighlight>
{{out}}
<pre>'broood' encodes to [1, 17, 15, 0, 0, 5], which decodes back to 'broood'
'bananaaa' encodes to [1, 1, 13, 1, 1, 1, 0, 0], which decodes back to 'bananaaa'
'hiphophiphop' encodes to [7, 8, 15, 2, 15, 2, 2, 3, 2, 2, 3, 2], which decodes back to 'hiphophiphop'</pre>
 
=={{header|EasyLang}}==
{{trans|Ring}}
<syntaxhighlight>
subr init
symt$[] = strchars "abcdefghijklmnopqrstuvwxyz"
.
proc rot k . .
c$ = symt$[k]
for j = k downto 2
symt$[j] = symt$[j - 1]
.
symt$[1] = c$
.
func[] encode s$ .
init
for c$ in strchars s$
k = 1
while symt$[k] <> c$
k += 1
.
res[] &= k - 1
rot k
.
return res[]
.
func$ decode s[] .
init
for k in s[]
k += 1
c$ = symt$[k]
res$ &= c$
rot k
.
return res$
.
for word$ in [ "broood" "babanaaa" "hiphophiphop" ]
enc[] = encode word$
print word$ & " -> " & enc[]
if decode enc[] <> word$
print "error"
.
.
</syntaxhighlight>
{{out}}
<pre>
broood -> [ 1 17 15 0 0 5 ]
babanaaa -> [ 1 1 1 1 13 1 0 0 ]
hiphophiphop -> [ 7 8 15 2 15 2 2 3 2 2 3 2 ]
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule MoveToFront do
@table Enum.to_list(?a..?z)
Line 913 ⟶ 1,118:
IO.inspect enc = MoveToFront.encode(word)
IO.puts "#{word == MoveToFront.decode(enc)}\n"
end)</langsyntaxhighlight>
 
{{out}}
Line 931 ⟶ 1,136:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Move-to-front algorithm . Nigel Galloway: March 1st., 2021
let fN g=List.permute(fun n->match compare n g with 0->0 |1->n |_->n+1)
Line 938 ⟶ 1,143:
fG ((string n).ToCharArray()|>List.ofArray) ['a'..'z']
["broood";"bananaaa";"hiphophiphop"]|>List.iter(fun n->let i=encode n in let g=decode i in printfn "%s->%A->%s check=%A" n i g (n=g))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 946 ⟶ 1,151:
</pre>
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel locals make sequences ;
 
: to-front ( elt seq -- seq' ) over [ remove ] dip prefix ;
Line 963 ⟶ 1,168:
 
"broood" "bananaaa" "hiphophiphop"
[ "abcdefghijklmnopqrstuvwxyz" round-trip ] tri@</langsyntaxhighlight>
{{out}}
<pre>
Line 969 ⟶ 1,174:
bananaaa -> { 1 1 13 1 1 1 0 0 } -> bananaaa
hiphophiphop -> { 7 8 15 2 15 2 2 3 2 2 3 2 } -> hiphophiphop
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=4268c779c36def03ea10764630cdc401 Click this link to run this code]'''
<lang gambas>Public Sub Main()
Dim sToCode As String[] = ["broood", "bananaaa", "hiphophiphop"] 'Samples to process
Dim sHold As New String[] 'To store results
Dim siCount, siCounter, siPos As Short 'Various variables
Dim sOutput, sCode, sWork, sEach As String 'Various variables
 
For siCounter = 0 To sToCode.Max 'To loop through each 'Sample'
sCode = "abcdefghijklmnopqrstuvwxyz" 'Set sCode to default setting
For siCount = 1 To Len(sToCode[siCounter]) 'Loop through each letter in 'Sample'
sWork = Mid(sToCode[siCounter], siCount, 1) 'sWork to store the Letter
siPos = InStr(scode, sWork) - 1 'Find the position of the letter in sCode, -1 for '0' based array
sOutput &= Str(siPos) & " " 'Add the postion to sOutput
sCode = Mid(sCode, siPos + 1, 1) & Replace(sCode, sWork, "") 'sCode = the letter + the rest of sCode except the letter
Next
Print sToCode[siCounter] & " = " & sOutput 'Print the 'Sample' and the coded version
sHold.Add(Trim(sOutput)) 'Add the code to the sHold array
sOutput = "" 'Clear sOutput
Next
 
Print 'Print a blank line
 
For siCounter = 0 To sHold.Max 'To loop through each coded 'Sample'
sCode = "abcdefghijklmnopqrstuvwxyz" 'Set sCode to default setting
For Each sEach In Split(sHold[siCounter], " ") 'For each 'code' in coded 'Sample'
sWork = Mid(sCode, Val(sEach) + 1, 1) 'sWork = the decoded letter
sOutput &= sWork 'Add the decoded letter to sOutput
sCode = sWork & Replace(sCode, sWork, "") 'sCode = the decoded letter + the rest of sCode except the letter
Next
Print sHold[siCounter] & " = " & sOutput 'Print the coded and decoded result
sOutput = "" 'Clear sOutput
Next
 
End</lang>
Output:
<pre>
broood = 1 17 15 0 0 5
bananaaa = 1 1 13 1 1 1 0 0
hiphophiphop = 7 8 15 2 15 2 2 3 2 2 3 2
 
1 17 15 0 0 5 = broood
1 1 13 1 1 1 0 0 = bananaaa
7 8 15 2 15 2 2 3 2 2 3 2 = hiphophiphop
</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#define FAIL -1
 
sub mtf( s() as string, i as uinteger )
Line 1,117 ⟶ 1,276:
printind( ind() )
decode( s(), ind() )
printarr( s() )</langsyntaxhighlight>
{{out}}<pre>
1 17 15 0 0 5
Line 1,128 ⟶ 1,287:
hiphophiphop
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=4268c779c36def03ea10764630cdc401 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sToCode As String[] = ["broood", "bananaaa", "hiphophiphop"] 'Samples to process
Dim sHold As New String[] 'To store results
Dim siCount, siCounter, siPos As Short 'Various variables
Dim sOutput, sCode, sWork, sEach As String 'Various variables
 
For siCounter = 0 To sToCode.Max 'To loop through each 'Sample'
sCode = "abcdefghijklmnopqrstuvwxyz" 'Set sCode to default setting
For siCount = 1 To Len(sToCode[siCounter]) 'Loop through each letter in 'Sample'
sWork = Mid(sToCode[siCounter], siCount, 1) 'sWork to store the Letter
siPos = InStr(scode, sWork) - 1 'Find the position of the letter in sCode, -1 for '0' based array
sOutput &= Str(siPos) & " " 'Add the postion to sOutput
sCode = Mid(sCode, siPos + 1, 1) & Replace(sCode, sWork, "") 'sCode = the letter + the rest of sCode except the letter
Next
Print sToCode[siCounter] & " = " & sOutput 'Print the 'Sample' and the coded version
sHold.Add(Trim(sOutput)) 'Add the code to the sHold array
sOutput = "" 'Clear sOutput
Next
 
Print 'Print a blank line
 
For siCounter = 0 To sHold.Max 'To loop through each coded 'Sample'
sCode = "abcdefghijklmnopqrstuvwxyz" 'Set sCode to default setting
For Each sEach In Split(sHold[siCounter], " ") 'For each 'code' in coded 'Sample'
sWork = Mid(sCode, Val(sEach) + 1, 1) 'sWork = the decoded letter
sOutput &= sWork 'Add the decoded letter to sOutput
sCode = sWork & Replace(sCode, sWork, "") 'sCode = the decoded letter + the rest of sCode except the letter
Next
Print sHold[siCounter] & " = " & sOutput 'Print the coded and decoded result
sOutput = "" 'Clear sOutput
Next
 
End</syntaxhighlight>
Output:
<pre>
broood = 1 17 15 0 0 5
bananaaa = 1 1 13 1 1 1 0 0
hiphophiphop = 7 8 15 2 15 2 2 3 2 2 3 2
 
1 17 15 0 0 5 = broood
1 1 13 1 1 1 0 0 = bananaaa
7 8 15 2 15 2 2 3 2 2 3 2 = hiphophiphop
</pre>
 
=={{header|Go}}==
{{trans|Python}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,173 ⟶ 1,379:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,182 ⟶ 1,388:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.List (delete, elemIndex, mapAccumL)
 
import Data.Maybe (fromJust)
Line 1,206 ⟶ 1,412:
(,) <*> uncurry ((==) . fst) <$> -- Test that ((fst . fst) x) == snd x)
((,) <*> (decode . snd) <$>
((,) <*> encode <$> ["broood", "bananaaa", "hiphophiphop"]))</langsyntaxhighlight>
{{out}}
<pre>((("broood",[1,17,15,0,0,5]),"broood"),True)
Line 1,215 ⟶ 1,421:
 
Works in both languages:
<langsyntaxhighlight lang="unicon">procedure main(A)
every writes(s := !A, " -> [") do {
every writes(!(enc := encode(&lcase,s))," ")
Line 1,243 ⟶ 1,449:
procedure reorder(s1,s2,s3)
return s2||s1||s3
end</langsyntaxhighlight>
 
Sample run:
Line 1,256 ⟶ 1,462:
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">spindizzy=:3 :0
'seq table'=. y
ndx=.$0
Line 1,276 ⟶ 1,482:
end.
seq
)</langsyntaxhighlight>
 
Required examples:
 
<langsyntaxhighlight Jlang="j"> spindizzy 'broood';'abcdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
spindizzy 'bananaaa';'abcdefghijklmnopqrstuvwxyz'
1 1 13 1 1 1 0 0
spindizzy 'hiphophiphop';'abcdefghijklmnopqrstuvwxyz'
7 8 15 2 15 2 2 3 2 2 3 2</langsyntaxhighlight>
 
It's not clear, though, why anyone would think that this is any better than lookups against an unmodified symbol table.
Line 1,291 ⟶ 1,497:
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.LinkedList;
import java.util.List;
 
Line 1,330 ⟶ 1,536:
test("hiphophiphop", symTable);
}
}</langsyntaxhighlight>
{{out}}
<pre>broood: [1, 17, 15, 0, 0, 5]
Line 1,340 ⟶ 1,546:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">var encodeMTF = function (word) {
var init = {wordAsNumbers: [], charList: 'abcdefghijklmnopqrstuvwxyz'.split('')};
 
Line 1,370 ⟶ 1,576:
console.log(encoded);
console.log("from decoded:");
console.log(decoded);</langsyntaxhighlight>
{{out}}
<pre>from encoded:
Line 1,383 ⟶ 1,589:
=={{header|jq}}==
{{works with|jq|q.4}}
<langsyntaxhighlight lang="jq"># Input is the string to be encoded, st is the initial symbol table (an array)
# Output: the encoded string (an array)
def m2f_encode(st):
Line 1,401 ⟶ 1,607:
| [ (.[0] + [ $st[$ix] ]), [$st[$ix]] + $st[0:$ix] + $st[$ix+1:] ] )
| .[0]
| implode;</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">("abcdefghijklmnopqrstuvwxyz" | explode) as $ST
| ("broood", "bananaaa", "hiphophiphop")
| . as $string
Line 1,411 ⟶ 1,617:
| if $string == $decoded then "\($string) => \($encoded) => \($decoded)"
else "INTERNAL ERROR: encoding of \($string) => \($encoded) => \($decoded)"
end</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -r -n -f move_to_front.jq
broood => [1,17,15,0,0,5] => broood
bananaaa => [1,1,13,1,1,1,0,0] => bananaaa
hiphophiphop => [7,8,15,2,15,2,2,3,2,2,3,2] => hiphophiphop</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
<langsyntaxhighlight lang="julia">function encodeMTF(str::AbstractString, symtable::Vector{Char}=collect('a':'z'))
function encode(ch::Char)
r = findfirst(symtable, ch)
Line 1,452 ⟶ 1,658:
@test str == dec
end
end</langsyntaxhighlight>
 
{{out}}
Line 1,468 ⟶ 1,674:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun encode(s: String): IntArray {
Line 1,515 ⟶ 1,721:
println(" -> ${if (decoded[i] == strings[i]) "correct" else "incorrect"}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,529 ⟶ 1,735:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">-- Return table of the alphabet in lower case
function getAlphabet ()
local letters = {}
Line 1,574 ⟶ 1,780:
print("Decoded: " .. decode(output))
print()
end</langsyntaxhighlight>
{{out}}
<pre>Original string: broood
Line 1,603 ⟶ 1,809:
Number pop a number from stack of values, if no number found then raise error.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Global All$, nl$
Line 1,648 ⟶ 1,854:
}
CheckIt
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,715 ⟶ 1,921:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
<langsyntaxhighlight Mathematicalang="mathematica">mtf[word_]:=Module[{f,f2,p,q},
f[{output_,symList_},next_]:=Module[{index},index=Position[symList,next][[1,1]]-1;
{output~Append~index,Prepend[Delete[symList,index+1],next]}];
Line 1,722 ⟶ 1,928:
{output~Append~index,Prepend[DeleteCases[symList,ToString[index]],index]}];
q=Fold[f2,{{},CharacterRange["a","z"]},p][[1]];
Print["'", word,"' encodes to: ",p, " - " ,p," decodes to: '",StringJoin@q,"' - Input equals Output: " ,word===StringJoin@q];]</langsyntaxhighlight>
Testing out the function:
<langsyntaxhighlight Mathematicalang="mathematica">mtf /@ {"broood", "bananaaa", "hiphophiphop"}</langsyntaxhighlight>
{{out}}
<pre>'broood' encodes to: {1,17,15,0,0,5} - {1,17,15,0,0,5} decodes to: 'broood' - Input equals Output: True
Line 1,731 ⟶ 1,937:
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function testMTF
symTable = 'abcdefghijklmnopqrstuvwxyz';
inStr = {'broood' 'bananaaa' 'hiphophiphop'};
Line 1,760 ⟶ 1,966:
symTable = [symTable(arr(k)) symTable(1:arr(k)-1) symTable(arr(k)+1:end)];
end
end</langsyntaxhighlight>
{{out}}
<pre>broood: [ 1 17 15 0 0 5 ]
Line 1,770 ⟶ 1,976:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import algorithm, sequtils, strformat
 
const SymbolTable = toSeq('a'..'z')
Line 1,791 ⟶ 1,997:
let decoded = encoded.decode()
let status = if decoded == word: "correctly" else: "incorrectly"
echo &"'{word}' encodes to {encoded} which {status} decodes to '{decoded}'."</langsyntaxhighlight>
 
{{out}}
Line 1,799 ⟶ 2,005:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
sub encode {
Line 1,825 ⟶ 2,031:
print "correctly decoded to $decoded\n";
}
</syntaxhighlight>
</lang>
{{out}}
<pre>broood: 1 17 15 0 0 5
Line 1,836 ⟶ 2,042:
 
=={{header|Phix}}==
Equivalent longhand versions of the symtab reordering left in as comments
<lang Phix>function encode(string s)
<!--<syntaxhighlight lang="phix">(phixonline)-->
string symtab = "abcdefghijklmnopqrstuvwxyz"
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence res = {}
<span style="color: #008080;">function</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
for i=1 to length(s) do
<span style="color: #004080;">string</span> <span style="color: #000000;">symtab</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"abcdefghijklmnopqrstuvwxyz"</span>
integer ch = s[i]
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
integer k = find(ch,symtab)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
res &= k-1
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #000000;">symtab</span><span style="color: #0000FF;">)</span>
for j=k to 2 by -1 do
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
symtab[j] = symtab[j-1]
<span style="color: #000080;font-style:italic;">-- for j=k to 2 by -1 do
end for
-- symtab[1j] = chsymtab[j-1]
-- end for
-- symtab[1] = ch</span>
return res
<span style="color: #000000;">symtab</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">&</span><span style="color: #000000;">symtab</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
function decode(sequence s)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
string symtab = "abcdefghijklmnopqrstuvwxyz"
string res = ""
<span style="color: #008080;">function</span> <span style="color: #000000;">decode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
for i=1 to length(s) do
<span style="color: #004080;">string</span> <span style="color: #000000;">symtab</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"abcdefghijklmnopqrstuvwxyz"</span>
integer k = s[i]+1
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
integer ch = symtab[k]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
res &= ch
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">1</span>
for j=k to 2 by -1 do
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">symtab</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span>
symtab[j] = symtab[j-1]
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">ch</span>
end for
<span style="color: #000080;font-style:italic;">-- for j=k to 2 by -1 do
symtab[1] = ch
-- symtab[j] = symtab[j-1]
end for
-- return res end for
-- symtab[1] = ch</span>
end function
<span style="color: #000000;">symtab</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">&</span><span style="color: #000000;">symtab</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
procedure test(string s)
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
sequence e = encode(s)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
string d = decode(e)
?{s,e,d,{"**ERROR**","ok"}[(s=d)+1]}
<span style="color: #008080;">procedure</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #004080;">sequence</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
test("broood")
<span style="color: #004080;">string</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">decode</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">)</span>
test("bananaaa")
<span style="color: #0000FF;">?{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"**ERROR**"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ok"</span><span style="color: #0000FF;">}[(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">=</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]}</span>
test("hiphophiphop")</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"broood"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"bananaaa"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"hiphophiphop"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,883 ⟶ 2,094:
=={{header|PHP}}==
 
<langsyntaxhighlight PHPlang="php"><?php
 
function symbolTable() {
Line 1,926 ⟶ 2,137:
' : ', ($original === $decoded ? 'OK' : 'Error'),
PHP_EOL;
}</langsyntaxhighlight>
 
{{out}}
Line 1,932 ⟶ 2,143:
bananaaa -> [1,1,13,1,1,1,0,0] -> bananaaa : OK
hiphophiphop -> [7,8,15,2,15,2,2,3,2,2,3,2] -> hiphophiphop : OK</pre>
 
=={{header|Picat}}==
Picat has 1-based index so some adjustments was necessary.
<syntaxhighlight lang="picat">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.</syntaxhighlight>
 
{{out}}
<pre>pos = [1,17,15,0,0,5]
table = orbacdefghijklmnpqstuvwxyz
string2 = broood
same
 
pos = [1,1,13,1,1,1,0,0]
table = anbcdefghijklmopqrstuvwxyz
string2 = bananaaa
same
 
pos = [7,8,15,2,15,2,2,3,2,2,3,2]
table = ohpiabcdefgjklmnqrstuvwxyz
string2 = hiphophiphop
same</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de encode (Str)
(let Table (chop "abcdefghijklmnopqrstuvwxyz")
(mapcar
Line 1,952 ⟶ 2,225:
(get Table (inc 'N))
(rot Table N) ) )
Lst ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(test (1 17 15 0 0 5)
(encode "broood") )
(test "broood"
Line 1,967 ⟶ 2,240:
(encode "hiphophiphop") )
(test "hiphophiphop"
(decode (7 8 15 2 15 2 2 3 2 2 3 2)) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process source attributes xref or(!);
/*********************************************************************
* 25.5.2014 Walter Pachl translated from REXX
Line 2,009 ⟶ 2,282:
Else
Put Skip List('all wrong!!');
End;</langsyntaxhighlight>
{{out}}
<pre> in=broood
Line 2,030 ⟶ 2,303:
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">Function Test-MTF
{
[CmdletBinding()]
Line 2,104 ⟶ 2,377:
}
End{}
}</langsyntaxhighlight>
 
{{out}}
Line 2,120 ⟶ 2,393:
 
===Python: Procedural===
<langsyntaxhighlight lang="python">from __future__ import print_function
from string import ascii_lowercase
 
Line 2,147 ⟶ 2,420:
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!'</langsyntaxhighlight>
 
{{out}}
Line 2,158 ⟶ 2,431:
For the functional forms a 2-item list of output to be accumulated and symboltable manipulation is calculated then only the former accumulated as the later works to transform the symbol table in-place.
 
<langsyntaxhighlight lang="python">def m2f_e(s, st):
return [[st.index(ch), st.insert(0, st.pop(st.index(ch)))][0] for ch in s]
 
Line 2,170 ⟶ 2,443:
decode = m2f_d(encode, ST[::])
print('decodes back to %r' % decode)
assert s == decode, 'Whoops!'</langsyntaxhighlight>
 
{{out}}
Line 2,177 ⟶ 2,450:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ []
26 times
[ char a i^ +
Line 2,211 ⟶ 2,484:
 
$ "broood bananaaa hiphophiphop"
nest$ witheach task</langsyntaxhighlight>
 
{{out}}
Line 2,223 ⟶ 2,496:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(define default-symtab "abcdefghijklmnopqrstuvwxyz")
 
Line 2,267 ⟶ 2,540:
(printf "~s encodes to ~s, which decodes ~s to ~s.~%" str enc crt dec))
(for-each encode+decode-string '("broood" "bananaaa" "hiphophiphop")))</langsyntaxhighlight>
 
{{out}}
Line 2,277 ⟶ 2,550:
(formerly Perl 6)
{{works with|rakudo|2015-09-24}}
<syntaxhighlight lang="raku" perl6line>sub encode ( Str $word ) {
my @sym = 'a' .. 'z';
gather for $word.comb -> $c {
Line 2,299 ⟶ 2,572:
my $dec = decode($enc);
is $word, $dec, "$word.fmt('%-12s') ($enc[])";
}</langsyntaxhighlight>
{{out}}
<pre>1..3
Line 2,308 ⟶ 2,581:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 25.05.2014 Walter Pachl
* REXX strings start with position 1
Line 2,343 ⟶ 2,616:
Say 'all wrong!!'
Return
</syntaxhighlight>
</lang>
{{out}}
<pre> in=broood
Line 2,365 ⟶ 2,638:
===version 2===
Programming note: &nbsp; the two REXX statements that add/subtract &nbsp; <big> '''one''' </big>&nbsp; deal with the task's requirement that the symbol table be &nbsp; ''zero-indexed'' &nbsp; (the REXX language uses &nbsp; ''unity-based'' &nbsp; strings).
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates the move─to─front algorithm encode/decode symbol table. */
parse arg xxx; if xxx='' then xxx= 'broood bananaaa hiphophiphop' /*use the default?*/
one= 1 /*(offset) for this task's requirement.*/
Line 2,381 ⟶ 2,654:
end /*m*/ /* [↑] the move─to─front decoding. */
say ' word: ' left(x, 20) "encoding:" left($, 35) word('wrong OK', 1 + (!==x) )
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 2,390 ⟶ 2,663:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Move-to-front algorithm
 
Line 2,430 ⟶ 2,703:
d = decode(e)
see "" + s + " => " + "(" + right(e, len(e) - 1) + ") " + " => " + substr(d, " ", "") + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,440 ⟶ 2,713:
=={{header|Ruby}}==
Use a module as namespace:
<langsyntaxhighlight lang="ruby">module MoveToFront
ABC = ("a".."z").to_a.freeze
Line 2,469 ⟶ 2,742:
['broood', 'bananaaa', 'hiphophiphop'].each do |word|
p word == MoveToFront.decode(p MoveToFront.encode(p word))
end</langsyntaxhighlight>
 
{{out}}
Line 2,486 ⟶ 2,759:
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">fn main() {
let examples = vec!["broood", "bananaaa", "hiphophiphop"];
for example in examples {
Line 2,529 ⟶ 2,802:
.map(|c| c as char)
.collect()
}</langsyntaxhighlight>
 
{{out}}
Line 2,540 ⟶ 2,813:
=={{header|Scala}}==
{{works with|Scala|2.11.8+}}
<langsyntaxhighlight lang="scala">package rosetta
 
import scala.annotation.tailrec
Line 2,636 ⟶ 2,909:
MoveToFront.test("bananaaa", symTable)
MoveToFront.test("hiphophiphop", symTable)
}</langsyntaxhighlight>
{{out}}
<pre>broood: List(1, 17, 15, 0, 0, 5)
Line 2,648 ⟶ 2,921:
{{trans|Perl}}
Implemented using regular expressions:
<langsyntaxhighlight lang="ruby">func encode(str) {
var table = ('a'..'z' -> join);
str.chars.map { |c|
Line 2,672 ⟶ 2,945:
print "in" if (decoded != test);
say "correctly decoded to #{decoded}";
}</langsyntaxhighlight>
 
Alternatively, implemented as a module, using arrays:
<langsyntaxhighlight lang="ruby">module MoveToFront {
 
define ABC = @("a".."z")
Line 2,710 ⟶ 2,983:
print "in" if (decoded != test);
say "correctly decoded to #{decoded}";
}</langsyntaxhighlight>
 
{{out}}
Line 2,723 ⟶ 2,996:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">
 
var str="broood"
Line 2,794 ⟶ 3,067:
print(encarr)
print(decarr)
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
oo::class create MoveToFront {
Line 2,836 ⟶ 3,109:
puts [format "'%s' encodes to %s. This decodes to '%s'. %s" \
$tester $enc $dec [expr {$tester eq $dec ? "Correct!" : "WRONG!"}]]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,845 ⟶ 3,118:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">Function mtf_encode(s)
'create the array list and populate it with the initial symbol position
Set symbol_table = CreateObject("System.Collections.ArrayList")
Line 2,893 ⟶ 3,166:
mtf_decode(mtf_encode(word)) & "."
WScript.StdOut.WriteBlankLines(1)
Next</langsyntaxhighlight>
 
{{Out}}
Line 2,906 ⟶ 3,179:
{{libheader|Wren-fmt}}
{{libheader|Wren-seq}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./seq" for Lst
 
var encode = Fn.new { |s|
Line 2,960 ⟶ 3,233:
Fmt.print("$-38n -> $-12s -> $s", a, decoded[i], correct)
i = i + 1
}</langsyntaxhighlight>
 
{{out}}
Line 2,974 ⟶ 3,247:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn encode(text){ //-->List
st:=["a".."z"].pump(Data); //"abcd..z" as byte array
text.reduce(fcn(st,c,sink){
n:=st.index(c); sink.write(n); st.del(n).insert(0,c); },st,sink:=L());
sink;
}</langsyntaxhighlight>
Strings are immutable so we create a bit bucket (which is mutable) to hold the symbol table which can then be modified in place.
<langsyntaxhighlight lang="zkl">fcn decode(list){ //-->String
st:=["a".."z"].pump(String); //"abcd..z"
sink:=Sink(String);
list.reduce('wrap(st,n){ c:=st[n]; sink.write(c); c+st.del(n); },st);
sink.close();
}</langsyntaxhighlight>
Here, we create a new symbol table each round as we would have to convert the byte we got from the bit bucket to string (so it is a wash garbage wise).
<langsyntaxhighlight lang="zkl">texts:=T("broood","bananaaa","hiphophiphop");
out:=texts.apply(encode);
texts.zipWith(fcn(t,e){ println(t,"-->",e) },out);
 
out.apply(decode).println();
texts.zipWith('==,out.apply(decode)).println();</langsyntaxhighlight>
{{out}}
<pre>
2,023

edits