RosettaCodeData/Task/Move-to-front-algorithm/Sidef/move-to-front-algorithm-2.s...

37 lines
674 B
Plaintext

module MoveToFront {
define ABC = @("a".."z")
func m2f(ar,i) {
[ar.delete_index(i)] + ar
}
func encode(str) {
var ar = ABC+[]
gather {
str.each_char { |char|
take(var i = ar.index(char))
ar = m2f(ar, i);
}
}
}
func decode(indices) {
var ar = ABC+[]
gather {
indices.each { |i|
take ar[i];
ar = m2f(ar, i)
}
}.join
}
}
%w(broood bananaaa hiphophiphop).each { |test|
var encoded = MoveToFront::encode(test);
say "#{test}: #{encoded}";
var decoded = MoveToFront::decode(encoded);
print "in" if (decoded != test);
say "correctly decoded to #{decoded}";
}