Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

Реши пожалуйста на Java. Реализуйте публичные статические методы rotateLeft() и…

  1. User

    Реши пожалуйста на Java. Реализуйте публичные статические методы rotateLeft() и rotateRight(), которые поворачивают матрицу влево (против часовой стрелки) и соответственно вправо (по часовой стрелке). Матрица представляет собой двумерный массив целых чисел. Методы должны возвращать новую матрицу, не изменяя исходную.

  2. Assistant
    public class MatrixRotation {
        public static int[][] rotateLeft(int[][] matrix) {
            int rows = matrix.length;
            int cols = matrix[0].length;
            int[][] rotatedMatrix = new int[cols][rows];
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    rotatedMatrix[cols - j - 1][i] = matrix[i][j];
                }
            }
            return rotatedMatrix;
        }
    
        public static int[][] rotateRight(int[][] matrix) {
            int rows = matrix.length;
            int cols = matrix[0].length;
            int[][] rotatedMatrix = new int[cols][rows];
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    rotatedMatrix[j][rows - i - 1] = matrix[i][j];
                }
            }
            return rotatedMatrix;
        }
    }