#!/usr/bin/ruby

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

func permute (code, arr) {
    var idx = arr.keys;

    while (true) {
        code(arr.items(idx...));

        var p = idx.end;
        while (idx[p - 1] > idx[p]) { --p };
        p == 0 && return();

        idx += idx.splice(p).reverse;

        var d = p;
        while (idx[p - 1] > idx[d]) { ++d };
        idx[p-1, d] = idx[d, p-1];
    }
}

var name = %c"abc";
permute(func (list) { list.join(' ').say }, name);
