Move-to-front algorithm: Difference between revisions
Add Factor example
Thundergnat (talk | contribs) m (→{{header|Ring}}: Remove vanity tags) |
(Add Factor example) |
||
Line 892:
[7, 8, 15, 2, 15, 2, 2, 3, 2, 2, 3, 2]
true
</pre>
=={{header|Factor}}==
<lang factor>USING: formatting kernel locals make sequences ;
: to-front ( elt seq -- seq' ) over [ remove ] dip prefix ;
: encode ( symbols msg -- indices )
[ [ swap 2dup index , to-front ] each ] { } make nip ;
: decode ( symbols indices -- msg )
[ [ swap [ nth ] keep over , to-front ] each ] "" make nip ;
:: round-trip ( symbols msg -- )
symbols msg encode :> encoded
symbols encoded decode :> decoded
msg encoded decoded "%s -> %u -> %s\n" printf ;
"broood" "bananaaa" "hiphophiphop"
[ "abcdefghijklmnopqrstuvwxyz" swap round-trip ] tri@</lang>
{{out}}
<pre>
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
</pre>
|