ruby - Can not initialize array correctly -


i've been trying code algorithm in minified manner>. believe typical 2d array defining looks unwieldy

 mx = array.new(n) { array.new(n) } 

i trying use hint, it's behaviour bit strange me:

 mx = [[!:&]*n]*n 

take look:

#square matrix n*n n=3 mx = [[!:&]*n]*n #=> [[false, false, false], [false, false, false], [false, false, false]]  mx[0][0]=true         mx #=> [[true, false, false], [true, false, false], [true, false, false]] #     true                  true                  true ???? #. 

how should tame array? repl.it_snippet: avaiable

this because sub arrays same instance

#square matrix n*n  n=3 mx = [[!:&]*n]*n #=> [[false, false, false], [false, false, false], [false, false, false]]  mx[0] === mx[1] # true  mx[1] === mx[2] # true 

to fix code, add that

n=3 mx = [[!:&]*n]*n mx = mx.flatten.each_slice(n).to_a mx[0][0] = true mx # [[true, false, false], [false, false, false], [false, false, false]] 

or

n=3 mx = ([!:&]*n*n).each_slice(n).to_a mx[0][0] = true mx # [[true, false, false], [false, false, false], [false, false, false]] 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -