How do you rotate a two dimensional array?

后端 未结 30 3102
耶瑟儿~
耶瑟儿~ 2020-11-22 02:43

Inspired by Raymond Chen\'s post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I\'d

30条回答
  •  梦如初夏
    2020-11-22 03:34

    Here's my Ruby version (note the values aren't displayed the same, but it still rotates as described).

    def rotate(matrix)
      result = []
      4.times { |x|
        result[x] = []
        4.times { |y|
          result[x][y] = matrix[y][3 - x]
        }
      }
    
      result
    end
    
    matrix = []
    matrix[0] = [1,2,3,4]
    matrix[1] = [5,6,7,8]
    matrix[2] = [9,0,1,2]
    matrix[3] = [3,4,5,6]
    
    def print_matrix(matrix)
      4.times { |y|
        4.times { |x|
          print "#{matrix[x][y]} "
        }
        puts ""
      }
    end
    
    print_matrix(matrix)
    puts ""
    print_matrix(rotate(matrix))
    

    The output:

    1 5 9 3 
    2 6 0 4 
    3 7 1 5 
    4 8 2 6 
    
    4 3 2 1 
    8 7 6 5 
    2 1 0 9 
    6 5 4 3
    

提交回复
热议问题