brabuhr
6/14/2009 4:56:00 PM
Hope this isn't too early, but I may be offline for a couple of days,
so I'm posting my method now:
> ## Matrix Rotator (#209)
>
> This week's quiz is write ruby method that will rotate a matrix 90
> degrees counter-clockwise (or =F0/2 radians).
>
> Ex:
> =A0 =A00 0 0 0 0 0 0 0
> =A0 =A00 X 0 0 0 0 X 0
> =A0 =A0X X X 0 0 X X 0
> =A0 =A00 0 0 0 0 0 X 0
module Matrix
def self.rotate(o)
rows, cols =3D o.size, o[0].size
Array.new(cols){|i| Array.new(rows){|j| o[j][cols - i - 1]}}
end
end
3 tests, 5 assertions, 0 failures, 0 errors:
assert_equal square_rotated, Matrix.rotate(square)
assert_equal rectangle_rotated, Matrix.rotate(rectangle)
assert_equal( [[5], [4], [3], [2], [1]], Matrix.rotate([(1..5).to_a]) )
assert_equal( [[1, 2, 3, 4, 5]], Matrix.rotate((1..5).to_a.map{|n| [n]}=
) )
assert_equal(
[ [1, 2, 3, 4, 5],
[6, 7, 8, 9, 0] ],
Matrix.rotate([ [6, 1], [7, 2], [8, 3], [9, 4], [0, 5] ])
)