Contact: aviboots(AT)netvision.net.il
41,366 questions
53,898 answers
573 users
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] t = matrix.transpose t.each { |row| puts row.join(" ") } # run: # # 1 4 7 # 2 5 8 # 3 6 9 #
def transpose(matrix) rows = matrix.length cols = matrix[0].length result = Array.new(cols) { Array.new(rows) } (0...rows).each do |i| (0...cols).each do |j| result[j][i] = matrix[i][j] end end result end matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] transpose(matrix).each { |row| puts row.join(" ") } # run: # # 1 4 7 # 2 5 8 # 3 6 9 #
# Functional (using map) def transpose(matrix) matrix[0].map.with_index { |_, i| matrix.map { |row| row[i] } } end matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] transpose(matrix).each { |row| puts row.join(" ") } # run: # # 1 4 7 # 2 5 8 # 3 6 9 #