0

Though part of my question has been answered in this thread;

Finding all possible combinations of numbers to reach a given sum

there is one further function I'm looking for.

Scrolling down on that page for the ruby solution and more importantly the final line,

subset_sum([3,9,8,4,5,7,10],15)

I was wondering how you would go through multiple arrays, picking just one number from each array and coming to a set value. The reason I ask is because I play a game called Heroclix. Each piece has a certain point value attributed to it and players make teams in multiples of one hundreds. What I'm looking to avoid is using the same named character more than once in a team, just because they just so happen to have various point costs.

Community
  • 1
  • 1
  • 1
    @sawa's right that you should state your question here. In fact, I see no point to even mention the earlier question. How about, "Given an array `arr` of arrays of numbers, I wish to determine if I can select one number from each element (array) of `arr` such that the sum of those numbers equals a given total". If the numbers are non-negative or positive, you should say so. – Cary Swoveland May 09 '16 at 01:27
  • I did not make it clear that you need to edit it your question. – Cary Swoveland May 09 '16 at 01:43
  • Did I answer your question? – Cary Swoveland May 12 '16 at 01:59

1 Answers1

0
arr = [[1,2,3], [5,7,8], [4,9,13]]
target = 19

If you want just one solution:

arr[0].product(*arr[1..-1]).find { |a| a.reduce(:+) == target }
  #=> [1, 5, 13]

If you want all solutions:

arr[0].product(*arr[1..-1]).select { |a| a.reduce(:+) == target }
  #=> [[1, 5, 13], [2, 8, 9], [3, 7, 9]]

For both:

arr[0].product(*arr[1..-1])
  #=> [[1, 5, 4], [1, 5, 9], [1, 5, 13], [1, 7, 4], [1, 7, 9], [1, 7, 13],
  #    [1, 8, 4], [1, 8, 9], [1, 8, 13], [2, 5, 4], [2, 5, 9], [2, 5, 13],
  #    [2, 7, 4], [2, 7, 9], [2, 7, 13], [2, 8, 4], [2, 8, 9], [2, 8, 13],
  #    [3, 5, 4], [3, 5, 9], [3, 5, 13], [3, 7, 4], [3, 7, 9], [3, 7, 13],
  #    [3, 8, 4], [3, 8, 9], [3, 8, 13]]

See Array#product.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100