0

I have an array @ary = [1, 3, 4, 2, 7, 8, 9] and I want to know how many possibilities of combination can add equal to 9.

I should have four possibilities can add equal to 9 [1,8][2, 3, 4][9][2, 7],but in my code, I just can know two of possibilities and just can show one possibility in this problem.

def sums (num, target)
 random1 = num.sample
 random2 = num.sample
 if random1+random2 == target
   ary1 = [random1, random2]
 end
end
Champer Wu
  • 1,101
  • 3
  • 13
  • 32
  • 1
    Is there something you have tried? Please show that you've made an attempt to solve the problem. – Mark Thomas May 03 '17 at 12:42
  • To be fair, that "duplicate" is not an answer in ruby... But you can't really ask such a broad question, in a specific language, without showing your attempt at a solution first. – Tom Lord May 03 '17 at 12:48
  • @MarkThomas I edit my question , and it's my try – Champer Wu May 03 '17 at 12:57
  • @TomLord I'm sorry about the mistake, I have the code about the question, but I think there are not really hit the question core, so I don't know should me put it on my question. – Champer Wu May 03 '17 at 13:03

2 Answers2

3

You can use Array#combination:

(1..ary.size).inject(0) do |a, e| 
  a + ary.combination(e).count { |e| e.sum == 9 } 
end
#=> 4

You can use inject(:+) instead of sum if your ruby version is lower than 2.4.

Ilya
  • 13,337
  • 5
  • 37
  • 53
  • 1
    @ndn: It sometimes happens. It seems that if you begin to write an answer before the question is closed, your browser might not notice the question has been closed by the time the answer is finished. Don't ask me why the server accepts the answer, though. – Eric Duminil May 03 '17 at 12:54
  • 1
    Note that `Array#sum` is only included in `ActiveSupport` (e.g. Rails projects), or in ruby version `2.4+`. In lower versions of ruby, without `require 'active_support/core_ext/enumerable.rb'` or `require 'active_support/all'`, you need to use `.inject(:+)`. – Tom Lord May 03 '17 at 12:55
  • Why do you assign to `a`? It is a local variable (more precisely, a parameter binding, but those behave like local variables), and thus goes out of scope at the end of the block (i.e. immediately after the assignment) anyway. – Jörg W Mittag May 03 '17 at 18:34
  • @JörgWMittag, I missed this, of course, the assignment is useless here. – Ilya May 03 '17 at 20:25
3

If you're interested in the combinations themselves as opposed to just the count:

(1..a.size).flat_map { |n| a.combination(n).to_a }
  .keep_if { |c| c.inject(:+) == 9 }

#=> [[9], [1, 8], [2, 7], [3, 4, 2]]
  • 1
    Creates a large intermediate Array may not be suitable for bigger data sets. Very clean solution for the given problem though – engineersmnky May 03 '17 at 13:25