im trying to find all possible sums using numbers from the testArray. i am assigning arrays to a hash, it uses sum as key and stores the integers from testArray that add up to the sum:
testArray=[1,2,3,4] @possibleSums=Hash.new {|h,k| h[k] = [] } for j in 0..testArray.size-1 tmpSum=0 output="" @sumArray=[] for k in j..testArray.size-1 tmpSum=tmpSum+testArray[k] output=output+"+"+testArray[k].to_s @sumArray.push(testArray[k]) @possibleSums[tmpSum]=@sumArray p output+"="+tmpSum.to_s end end the problem is that i noticed that as @sumArray changes through every iteration of the loop, the previous recorded hash key value also changes. what am i doing wrong?
example:
output: "+1=1" @sumArray: [1] @possibleSums: {1=>[1]} output: "+1+2=3" @sumArray: [1, 2] @possibleSums: {1=>[1, 2], 3=>[1, 2]} output: "+1+2+3=6" @sumArray: [1, 2, 3] @possibleSums: {1=>[1, 2, 3], 3=>[1, 2, 3], 6=>[1, 2, 3]} you can see that value of key 1 and 3 kept changing with @sumArray
@sumArrayin the hash.@possibleSums[tmpSum][email protected]insteadtest_array=[1,3,7,10]is as follows:require 'set'; (1..test_array.size).each_with_object(Set.new) { |n,st| test_array.combination(n).each { |a| st << a.sum } }.to_a #=> [1, 3, 7, 10, 4, 8, 11, 13, 17, 14, 18, 20, 21]. I wrotetest_arrayrather thantestArraybecause, by convention, Ruby uses snake case for names of variables and methods.