Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combination up to n

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]]
like image 673
sawa Avatar asked Feb 27 '14 12:02

sawa


People also ask

What is the n in combination?

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.

What is n in permutation and combination?

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?

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.

How many combinations of 7 numbers are there?

Answer and Explanation: The number of combinations that are possible with 7 numbers is 127.


2 Answers

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"]]
like image 59
Arup Rakshit Avatar answered Oct 01 '22 16:10

Arup Rakshit


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], []]
like image 34
Cary Swoveland Avatar answered Oct 01 '22 17:10

Cary Swoveland