Combinations

Built-in

combinations(5, 3, {|*c| say c })

Recursive

func combine(n, set) {

    set.len || return []
    n == 1  && return set.map{[_]}

    var (head, result)
    head   = set.shift
    result = combine(n-1, [set...])

    for subarray in result {
        subarray.prepend(head)
    }

    result + combine(n, set)
}

combine(3, @^5).each {|c| say c }

Iterative

Output

Last updated

Was this helpful?