0

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

4
  • 3
    You are putting a reference to @sumArray in the hash. Commented Sep 12, 2021 at 17:48
  • 2
    red_menace is right .. you can use @possibleSums[tmpSum][email protected] instead Commented Sep 12, 2021 at 18:12
  • A more Ruby-like way to obtain an array of all sums for test_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 wrote test_array rather than testArray because, by convention, Ruby uses snake case for names of variables and methods. Commented Sep 12, 2021 at 19:58
  • 1
    so @possibleSums[tmpSum][email protected] is the proper way to assign instance of an array to a hash? Commented Sep 12, 2021 at 22:16

1 Answer 1

0

You are putting a reference to @sumArray in the hash. – red_menace Sep 12 at 17:48

red_menace is right .. you can use @possibleSums[tmpSum][email protected] instead

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

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.