#!/usr/bin/ruby

#
## https://rosettacode.org/wiki/Rice_coding
#

func rice(k, arr) {
    var t = 2**k
    arr.map {|v|
        ['1' * (v >> k), '0', '%0*s' % (k, as_bin(v % t))].join
    }.join
}

func derice(k, str) {
    gather {
        var re = Regex('\G(1*)0(.{' + Str(k) + '})', 'g')
        while (str =~ re) {|m|
            take((m[0].len << k) + Num(m[1], 2))
        }
    }
}

for k in (2 .. 6) {
    say "\nk = #{k}\n"
    var input = @(0..17).shuffle
    var enc = rice(k, input)
    var dec = derice(k, enc)
    say "  input: #{input}"
    say "   rice: #{enc}"
    say "decoded: #{dec}"
    assert_eq(dec, input)
}
