I'm trying to transpose [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
. I get [[2, 5, 8], [2, 5, 8], [2, 5, 8]]
.
我试图转置[[0,1,2],[3,4,5],[6,7,8]]。我得到[[2,5,8],[2,5,8],[2,5,8]]。
I can see what is happening with the line p transposed_arr
but do not understand why this is happening. At every iteration it changes every row instead of only one.
我可以看到行p transposed_arr发生了什么,但不明白为什么会发生这种情况。在每次迭代时,它都会更改每一行而不是一行。
def my_transpose(arr)
# number of rows
m = arr.count
#number of columns
n = arr[0].count
transposed_arr = Array.new(n, Array.new(m))
# loop through the rows
arr.each_with_index do |row, index1|
# loop through the colons of one row
row.each_with_index do |num, index2|
# swap indexes to transpose the initial array
transposed_arr[index2][index1] = num
p transposed_arr
end
end
transposed_arr
end
1 个解决方案
#1
3
You need to make only one wee change and your method will work fine. Replace:
你需要只进行一次改变,你的方法才能正常工作。更换:
transposed_arr = Array.new(n, Array.new(m))
with:
有:
transposed_arr = Array.new(n) { Array.new(m) }
The former makes transposed_arr[i]
the same object (an array of size m
) for all i
. The latter creates a separate array of size m
for each i
前者使transposed_arr [i]成为所有i的相同对象(大小为m的数组)。后者为每个i创建一个单独的大小为m的数组
Case 1:
情况1:
transposed_arr = Array.new(2, Array.new(2))
transposed_arr[0].object_id
#=> 70235487747860
transposed_arr[1].object_id
#=> 70235487747860
Case 2:
案例2:
transposed_arr = Array.new(2) { Array.new(2) }
transposed_arr[0].object_id
#=> 70235478805680
transposed_arr[1].object_id
#=> 70235478805660
With that change your method returns:
通过该更改,您的方法返回:
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]
#1
3
You need to make only one wee change and your method will work fine. Replace:
你需要只进行一次改变,你的方法才能正常工作。更换:
transposed_arr = Array.new(n, Array.new(m))
with:
有:
transposed_arr = Array.new(n) { Array.new(m) }
The former makes transposed_arr[i]
the same object (an array of size m
) for all i
. The latter creates a separate array of size m
for each i
前者使transposed_arr [i]成为所有i的相同对象(大小为m的数组)。后者为每个i创建一个单独的大小为m的数组
Case 1:
情况1:
transposed_arr = Array.new(2, Array.new(2))
transposed_arr[0].object_id
#=> 70235487747860
transposed_arr[1].object_id
#=> 70235487747860
Case 2:
案例2:
transposed_arr = Array.new(2) { Array.new(2) }
transposed_arr[0].object_id
#=> 70235478805680
transposed_arr[1].object_id
#=> 70235478805660
With that change your method returns:
通过该更改,您的方法返回:
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]