Move-to-front algorithm: Difference between revisions
Content added Content deleted
Alextretyak (talk | contribs) (Added 11l) |
|||
Line 1,645: | Line 1,645: | ||
hiphophiphop: [ 7 8 15 2 15 2 2 3 2 2 3 2 ] |
hiphophiphop: [ 7 8 15 2 15 2 2 3 2 2 3 2 ] |
||
correctly decoded to hiphophiphop</pre> |
correctly decoded to hiphophiphop</pre> |
||
=={{header|Nim}}== |
|||
<lang Nim>import algorithm, sequtils, strformat |
|||
const SymbolTable = toSeq('a'..'z') |
|||
func encode(s: string): seq[int] = |
|||
var symtable: seq[char] = SymbolTable |
|||
for c in s: |
|||
let idx = symtable.find(c) |
|||
result.add idx |
|||
symtable.rotateLeft(0..idx, -1) |
|||
func decode(s: seq[int]): string = |
|||
var symtable = SymbolTable |
|||
for idx in s: |
|||
result.add symtable[idx] |
|||
symtable.rotateLeft(0..idx, -1) |
|||
for word in ["broood", "babanaaa", "hiphophiphop"]: |
|||
let encoded = word.encode() |
|||
let decoded = encoded.decode() |
|||
let status = if decoded == word: "correctly" else: "incorrectly" |
|||
echo &"'{word}' encodes to {encoded} which {status} decodes to '{decoded}'."</lang> |
|||
{{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|Perl}}== |
=={{header|Perl}}== |