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}"
}

Output:

First 20 of the sequence generated by [1, 2]:
[1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1]
Possible Kolakoski sequence? true

First 20 of the sequence generated by [2, 1]:
[2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2]
Possible Kolakoski sequence? true

First 30 of the sequence generated by [1, 3, 1, 2]:
[1, 3, 3, 3, 1, 1, 1, 2, 2, 2, 1, 3, 1, 2, 2, 1, 1, 3, 3, 1, 2, 2, 2, 1, 3, 3, 1, 1, 2, 1]
Possible Kolakoski sequence? true

First 30 of the sequence generated by [1, 3, 2, 1]:
[1, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 3, 3, 2, 2, 1, 1, 3, 2, 1, 1, 1, 1, 3, 3, 3, 2, 2, 1]
Possible Kolakoski sequence? false

Last updated