Given an array a
, what is the best way to achieve its combinations up to the n
-th? For example:
a = %i[a b c]
n = 2
# Expected => [[], [:a], [:b], [:c], [:a, b], [:b, :c], [:c, :a]]
n = the number of items. r = how many items are taken at a time. The ! symbol is a factorial, which is a number multiplied by all of the numbers before it.
The number of ways of arranging the objects or the number of permutations of n objects taken r number of objects at a time is given by: nPr = n!/(n – r)! Here, n represents the total number of objects or elements of the set and r represents the number of objects taken for permutations.
Is n choose k combination or permutation? The binomial coefficient {n \choose k} essentially comes under combination. The formula computes the different ways in which different combinations of k items can be chosen out of n items.
Answer and Explanation: The number of combinations that are possible with 7 numbers is 127.
Do as below :
a = %w[a b c]
n = 3
0.upto(n).flat_map { |i| a.combination(i).to_a }
# => [[], ["a"], ["b"], ["c"], ["a", "b"],
# ["a", "c"], ["b", "c"], ["a", "b", "c"]]
Another way:
def all_combis(a, n, b=[])
n.zero? ? b.unshift([]) : all_combis(a, n-1, b.unshift(*a.combination(n)))
end
all_combis(%i[a b c], 0)
#=> [[]]
all_combis(%i[a b c], 1)
#=> [[], [:a], [:b], [:c]]
all_combis(%i[a b c], 2)
#=> [[], [:a], [:b], [:c], [:a, :b], [:a, :c], [:b, :c]]
all_combis(%i[a b c], 3)
#=> [[], [:a], [:b], [:c], [:a, :b], [:a, :c], [:b, :c], [:a, :b, :c]]
If order and efficiency are unimportant, this also works:
a.repeated_combination(n).map(&:uniq) << []
%i[a b c].repeated_combination(2).map(&:uniq) << []
#=> [[:a], [:a, :b], [:a, :c], [:b], [:b, :c], [:c], []]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With