Move-to-front algorithm: Difference between revisions

Added zkl
No edit summary
(Added zkl)
Line 587:
st=pohiabcdefgjklmnqrstuvwxyz symbol table after encoding
out=hiphophiphop</pre>
 
=={{header|zkl}}==
<lang zkl>fcn encode(text){ //-->List
st:=["a".."z"].aggregate(String).walk().toData().copy(); //"abcd..z"
text.reduce(fcn(st,c,sink){
n:=st.index(c); sink.write(n); st.del(n).insert(0,c); },st,sink:=L());
sink;
}</lang>
String are immutable so we create a bit bucket (which is mutable) to hold the symbol table which can then be modified in place.
<lang zkl>fcn decode(list){ //-->String
st:=["a".."z"].aggregate(String).walk(); //"abcd..z"
sink:=Sink(String);
list.reduce('wrap(st,n){ c:=st[n]; sink.write(c); c+st.del(n); },st);
sink.close();
}></lang>
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).
<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();</lang>
{{out}}
<pre>
broood-->L(1,17,15,0,0,5)
bananaaa-->L(1,1,13,1,1,1,0,0)
hiphophiphop-->L(7,8,15,2,15,2,2,3,2,2,3,2)
L("broood","bananaaa","hiphophiphop")
L(True,True,True)
</pre>
Anonymous user