#!/usr/bin/ruby

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

func create_generator(arr) {
    Enumerator({|f|
        var s = []
        var i = 0
        loop {
            var t = arr[i++ % arr.len]
            s << t
            f(var v = s.shift)
            s << (v-1).of(t)...
        }
    })
}
 
var tests = [
    [20, [1,2]],
    [20, [2,1]],
    [30, [1,3,1,2]],
    [30, [1,3,2,1]]
]
 
for num,arr in (tests) {
    say "\nFirst #{num} of the sequence generated by #{arr}:"
    var res = create_generator(arr).first(num)
    var rle = res.run_length.map{.tail}
    say "#{res}\nPossible Kolakoski sequence? #{res.first(rle.len) == rle}"
}
