All I want to do is swap matrix[i][j]
with matrix[j][i]
using while
loops. Why doesn't this work?
def my_transpose(matrix)
new_matrix = []
i = 0
j = 0
while i < matrix.size
new_matrix[i] = []
while j < matrix.size
new_matrix[i] << matrix[j][i]
j += 1
end
i += 1
end
return new_matrix
end
If I run this with something like
[
[1,2,3],
[1,2,3],
[1,2,3]
]
it just returns 1,1,1
. How do I get it to return 1,1,1; 2,2,2; 3,3,3
?
If your question is How to swap columns and rows in a matrix with Ruby, the answer is to use the built-in Array#transpose
a = [
[1,2,3],
[1,2,3],
[1,2,3]
]
#=> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
a.transpose
#=> [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With