How to transpose a matrix (swap rows and columns) in Ruby

3 Answers

0 votes
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
#

 



answered 23 hours ago by avibootz
0 votes
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
#

 



answered 23 hours ago by avibootz
0 votes
# 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
#

 



answered 23 hours ago by avibootz
...