How do you rotate a two dimensional array?

后端 未结 30 3135
耶瑟儿~
耶瑟儿~ 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:23

    @dagorym: Aw, man. I had been hanging onto this as a good "I'm bored, what can I ponder" puzzle. I came up with my in-place transposition code, but got here to find yours pretty much identical to mine...ah, well. Here it is in Ruby.

    require 'pp'
    n = 10
    a = []
    n.times { a << (1..n).to_a }
    
    pp a
    
    0.upto(n/2-1) do |i|
      i.upto(n-i-2) do |j|
        tmp             = a[i][j]
        a[i][j]         = a[n-j-1][i]
        a[n-j-1][i]     = a[n-i-1][n-j-1]
        a[n-i-1][n-j-1] = a[j][n-i-1]
        a[j][n-i-1]     = tmp
      end
    end
    
    pp a
    

提交回复
热议问题