Combinations: Difference between revisions

Line 2,926:
[3, 4, 5]
</pre>
 
===Iterator Solution===
Alternatively, Julia's Iterators can be used for a very nice solution for any collection.
<syntaxhighlight lang="julia">
using Base.Iterators
function combinations(x::Vector{T}, size::Int)::Vector{Vector{T}} where T
# Iterators.filter(flt, itr) takes a function flt, and an iterator itr, and returns
# a new (lazy) iterator which passes elements for which flt returns true.
size_filter(x) = Iterators.filter(y -> count_ones(y) == size, x)
 
# Iterators.map(f, x) takes a function f and an iterable x, and returns
# a new (lazy) iterator which applies the function f to the elements of x.
bitstring_map(x) = Iterators.map(bitstring, x)
reverse_map(x) = Iterators.map(reverse, x)
 
# |> is a function pipe. The return value of the function before the pipe
# becomes the input value of the function after the pipe.
bit_strings = range(stop=2^length(x)-1) |>
size_filter |>
bitstring_map |>
reverse_map
# At this point, bit_strings is still a lazy iterator. It isn't until we
# collect the results into this array comprehension that the calculations
# are performed.
[[a for (a, b) in zip(x, bits) if b == '1'] for bits in bit_strings]
end
</syntaxhighlight>
{{out}}
<pre>
julia> show(combinations([1,2,3,4,5], 3))
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4], [1, 2, 5], [1, 3, 5], [2, 3, 5], [1, 4, 5], [2, 4, 5], [3, 4, 5]]
</pre>
end
 
=={{header|K}}==
7

edits