Permutations
Built-in
[0,1,2].permutations { |*a|
say a
}Iterative
func forperm(callback, n) {
var idx = @^n
loop {
callback(idx...)
var p = n-1
while (idx[p-1] > idx[p]) {--p}
p == 0 && return()
var d = p
idx += idx.splice(p).reverse
while (idx[p-1] > idx[d]) {++d}
idx.swap(p-1, d)
}
return()
}
forperm({|*p| say p }, 3)Recursive
Output:
Last updated
Was this helpful?