fork download
  1. # Simple implementation
  2. # (note that a method named #rotate already exists on Array, so there's some
  3. # risk of confusion)
  4. class Array
  5. def rotate_right
  6. transpose.map(&:reverse)
  7. end
  8.  
  9. def rotate_left
  10. map(&:reverse).transpose
  11. end
  12. end
  13.  
  14. # More general implementation
  15. class Array
  16. # Positive numbers rotate clockwise, negative number rotate counter-clockwise
  17. def rotated(times = 1)
  18. case times % 4
  19. when 1, -3
  20. transpose.map(&:reverse)
  21. when 2, -2
  22. reverse.map(&:reverse)
  23. when 3, -1
  24. map(&:reverse).transpose
  25. else
  26. self.dup # rotate 360; no change
  27. end
  28. end
  29. end
  30.  
  31. array = [[1, 2, 3],
  32. [4, 5, 6],
  33. [7, 8, 9]]
  34.  
  35. puts "Original array:"
  36. puts array.map { |row| row.map(&:to_s).join(" ") }
  37.  
  38. puts "Rotated once clockwise:"
  39. puts array.rotated.map { |row| row.map(&:to_s).join(" ") }
  40.  
  41. puts "Rotated once counter-clockwise:"
  42. puts array.rotated(-1).map { |row| row.map(&:to_s).join(" ") }
  43.  
  44. puts "Rotated twice:"
  45. puts array.rotated(2).map { |row| row.map(&:to_s).join(" ") }
  46.  
Success #stdin #stdout 0.02s 7464KB
stdin
Standard input is empty
stdout
Original array:
1 2 3
4 5 6
7 8 9
Rotated once clockwise:
7 4 1
8 5 2
9 6 3
Rotated once counter-clockwise:
3 6 9
2 5 8
1 4 7
Rotated twice:
9 8 7
6 5 4
3 2 1