Move-to-front algorithm:
mtf[string_] :=
Module[{word, p, q, symTable, symTable2},
p = {};
q = {};
symTable = StringJoin @@ CharacterRange["a", "z"];
Do[
If[
i == StringLength@string,
AppendTo[p,
StringPosition[symTable, StringTake[string, {i}]][[1, 1]] - 1];
symTable =
StringDrop[
symTable, {StringPosition[symTable, StringTake[string, {i}]][[1,
1]]}];
symTable = StringJoin[StringTake[string, {i}], symTable];
Print["'", string, "' encodes to: ", p],
AppendTo[p,
StringPosition[symTable, StringTake[string, {i}]][[1, 1]] - 1];
symTable =
StringDrop[
symTable, {StringPosition[symTable, StringTake[string, {i}]][[1,
1]]}];
symTable = StringJoin[StringTake[string, {i}], symTable];
]
, {i, StringLength@string}];
symTable = StringJoin @@ CharacterRange["a", "z"];
Do[
If[
j == StringLength@string,
q = StringJoin[q, StringTake[symTable, {p[[j]] + 1}]];
symTable2 =
StringDrop[
symTable, {StringPosition[symTable,
StringTake[symTable, {p[[j]] + 1}]][[1, 1]]}];
symTable =
StringJoin[StringTake[symTable, {p[[j]] + 1}], symTable2];
Print[p, " decodes to: '", q, "'"],
q = StringJoin[q, StringTake[symTable, {p[[j]] + 1}]];
symTable2 =
StringDrop[
symTable, {StringPosition[symTable,
StringTake[symTable, {p[[j]] + 1}]][[1, 1]]}];
symTable =
StringJoin[StringTake[symTable, {p[[j]] + 1}], symTable2]
]
, {j, StringLength@string}];
]
Any suggestions? Clunky code, but it gets the job done. Admittedly, I have cheated to get the problem "zero-indexed". This can apparently be done with the Notation package, but I haven't gotten a chance to look at it. Now back to my thesis!
In[347]:= Timing[mtf["broood"]]
During evaluation of In[347]:= 'broood' encodes to: {1,17,15,0,0,5}
During evaluation of In[347]:= {1,17,15,0,0,5} decodes to: 'broood'
Out[347]= {0.000612, Null}
Edit: I guess it's not a symbol table array either, it's just a string of the whole alphabet. Oh well.
Edit 2: Fixed the code. Good bug-catching!
mtf["zbmcfkukwmeogkhgkspansqgytihgwudpevgaelx"]
'zbmcfkukwmeogkhgkspansqgytihgwudpevgaelx' encodes to: {25,2,13,4,7,12,21,1,23,5,10,17,12,5,13,2,2,21,19,14,19,3,20,6,25,23,20,10,4,14,15,20,12,15,24,6,14,3,23,25}
{25,2,13,4,7,12,21,1,23,5,10,17,12,5,13,2,2,21,19,14,19,3,20,6,25,23,20,10,4,14,15,20,12,15,24,6,14,3,23,25} decodes to: 'zbmcfkukwmeogkhgkspansqgytihgwudpevgaelx'