#!/usr/bin/ruby

#
## http://rosettacode.org/wiki/Move-to-front_algorithm#Sidef
#

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}";
    assert_eq(test, decoded);
}
