2

I am trying to print all the different sums of all combinations in this array [1,2,3]. I want to first push every sum result to a new array b, then print them using b.uniq so that non of the sum results are repeated. However, with the code I have, the 3 repeats itself, and I think it is because of the way it is pushed into the array b.

Is there a better way of doing this?

a = [1,2,3]
b = []

b.push a

b.push a.combination(2).collect {|a,b| (a+b)}

b.push a.combination(3).collect {|a,b,c| (a+b+c)}

puts b.uniq
p b #[[1, 2, 3], [3, 4, 5], [6]] 

Can someone please help me with this? I am still new in ruby.

4
  • Do you need that array nesting in the result? Commented Oct 26, 2015 at 12:52
  • No I don't, I want to show them as separate values.. Commented Oct 26, 2015 at 12:53
  • then you could just p.flatten.uniq Commented Oct 26, 2015 at 12:54
  • But the first 3 you see, it's not a result of a sum operation. Commented Oct 26, 2015 at 13:12

2 Answers 2

3

Because an Array of arbitrary length can be summed using inject(:+), we can create a more general solution by iterating over the range 1..n, where n is the length of the Array.

(1..(a.size)).flat_map do |n|
  a.combination(n).map { |c| c.inject(&:+) }
end.uniq
#=> [1, 2, 3, 4, 5, 6]

By using flat_map, we can avoid getting the nested Array result, and can call uniq directly on it. Another option to ensure uniqueness would be to pass the result to a Set, for which Ruby guarantees uniqueness internally.

require "set"

sums = (1..(a.size)).flat_map do |n|
  a.combination(n).map { |c| c.inject(&:+) }
end

Set.new(sums)
#=> #<Set: {1, 2, 3, 4, 5, 6}>

This will work for an any Array, as long as all elements are Fixnum.

Sign up to request clarification or add additional context in comments.

Comments

0

If all you want is an array of the possible sums, flatten the array before getting the unique values.

puts b.flatten.uniq

What is happening is uniq is running over a multi-dimensional array. This causes it to look for duplicate arrays in your array. You'll need the array to be flattened first.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.