Rotating an image or matrix is a common operation in image processing and computer graphics. In Ruby, mastering the technique to rotate an NxN matrix by 90 degrees is essential for various applications. In this article, we’ll delve into how to implement a function in Ruby to achieve this rotation, accompanied by detailed examples and outputs to unravel the intricacies of image manipulation in programming.
Understanding Image Rotation
Rotating an image or matrix by 90 degrees involves shifting its elements in a clockwise or counterclockwise direction, creating a new transformed image or matrix.
Example: Rotating NxN Matrix in Ruby
Let’s define a Ruby function called rotate_image
to rotate an NxN matrix by 90 degrees.
def rotate_image(matrix)
n = matrix.length
(0...n / 2).each do |layer|
first = layer
last = n - 1 - layer
(first...last).each do |i|
offset = i - first
top = matrix[first][i]
# left -> top
matrix[first][i] = matrix[last - offset][first]
# bottom -> left
matrix[last - offset][first] = matrix[last][last - offset]
# right -> bottom
matrix[last][last - offset] = matrix[i][last]
# top -> right
matrix[i][last] = top
end
end
matrix
end
# Test the function with an example matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
puts "Original Matrix:"
matrix.each { |row| puts row.join(' ') }
puts "\nRotated Matrix:"
rotated_matrix = rotate_image(matrix)
rotated_matrix.each { |row| puts row.join(' ') }
Output:
Original Matrix:
1 2 3
4 5 6
7 8 9
Rotated Matrix:
7 4 1
8 5 2
9 6 3
In this example, the rotate_image
function correctly rotates the given matrix by 90 degrees clockwise, producing the desired output.