Contact
Back to Home

Describe the structure of a class that implements a matrix rotation function, including its inputs and return specifications.

Featured Answer

Question Analysis

The question asks for a description of a class structure that implements a matrix rotation function. This involves detailing the components necessary for the class to effectively rotate a matrix. We need to consider the inputs that the function will accept, the type of matrix rotation (e.g., 90 degrees clockwise or counterclockwise), and the return type of the function. Additionally, we should think about any helper methods or attributes that the class might need to facilitate the rotation.

Answer

To implement a matrix rotation function within a class, we need to define the following structure:

class MatrixRotator:
    def __init__(self, matrix):
        """
        Initializes the MatrixRotator with a given matrix.
        
        **Input:**
        - `matrix`: A 2D list representing the matrix to be rotated. 
          It should be a square matrix (n x n) for a standard rotation.
        """
        self.matrix = matrix
    
    def rotate_clockwise(self):
        """
        Rotates the input matrix 90 degrees clockwise.
        
        **Returns:**
        - A new matrix (2D list) which is the input matrix rotated 90 degrees clockwise.
        """
        n = len(self.matrix)
        rotated_matrix = [[0] * n for _ in range(n)]
        
        for i in range(n):
            for j in range(n):
                rotated_matrix[j][n - i - 1] = self.matrix[i][j]
        
        return rotated_matrix
    
    def rotate_counterclockwise(self):
        """
        Rotates the input matrix 90 degrees counterclockwise.
        
        **Returns:**
        - A new matrix (2D list) which is the input matrix rotated 90 degrees counterclockwise.
        """
        n = len(self.matrix)
        rotated_matrix = [[0] * n for _ in range(n)]
        
        for i in range(n):
            for j in range(n):
                rotated_matrix[n - j - 1][i] = self.matrix[i][j]
        
        return rotated_matrix

Key Points:

  • Inputs:

    • The class is initialized with a matrix, which is expected to be a 2D list representing a square matrix.
  • Methods:

    • rotate_clockwise: This method rotates the matrix 90 degrees clockwise.
    • rotate_counterclockwise: This method rotates the matrix 90 degrees counterclockwise.
  • Returns:

    • Each rotation method returns a new matrix that is the result of the rotation operation.

This class provides a clear and structured approach to rotating a matrix, allowing the user to easily rotate the matrix in either direction.