Move-to-front algorithm: Difference between revisions

Content added Content deleted
Line 1,129: Line 1,129:
bananaaa => [1,1,13,1,1,1,0,0] => bananaaa
bananaaa => [1,1,13,1,1,1,0,0] => bananaaa
hiphophiphop => [7,8,15,2,15,2,2,3,2,2,3,2] => hiphophiphop</lang>
hiphophiphop => [7,8,15,2,15,2,2,3,2,2,3,2] => hiphophiphop</lang>

=={{header|Julia}}==
{{works with|Julia|0.6}}
<lang julia>function encodeMTF(str::AbstractString, symtable::Vector{Char}=collect('a':'z'))
function encode(ch::Char)
r = findfirst(symtable, ch)
deleteat!(symtable, r)
prepend!(symtable, ch)
return r
end
collect(encode(ch) for ch in str)
end

function decodeMTF(arr::Vector{Int}, symtable::Vector{Char}=collect('a':'z'))
function decode(i::Int)
r = symtable[i]
deleteat!(symtable, i)
prepend!(symtable, r)
return r
end
join(decode(i) for i in arr)
end

testset = ["broood", "bananaaa", "hiphophiphop"]
encoded = encodeMTF.(testset)
decoded = decodeMTF.(encoded)
for (str, enc, dec) in zip(testset, encoded, decoded)
println("Test string: $str\n -> Encoded: $enc\n -> Decoded: $dec")
end

using Base.Test
@testset "Decoded string equal to original" begin
for (str, dec) in zip(testset, decoded)
@test str == dec
end
end</lang>

{{out}}
<pre>Test string: broood
-> Encoded: [2, 18, 16, 1, 1, 6]
-> Decoded: broood
Test string: bananaaa
-> Encoded: [2, 2, 14, 2, 2, 2, 1, 1]
-> Decoded: bananaaa
Test string: hiphophiphop
-> Encoded: [8, 9, 16, 3, 16, 3, 3, 4, 3, 3, 4, 3]
-> Decoded: hiphophiphop
Test Summary: | Pass Total
Decoded string equal to original | 3 3</pre>


=={{header|Kotlin}}==
=={{header|Kotlin}}==