Home > Mobile >  ruby hash array value changes when assigned array value changes
ruby hash array value changes when assigned array value changes

Time:09-16

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

CodePudding user response:

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

  • Related