Sort by

recency

|

770 Discussions

|

  • + 0 comments

    Python implementation within time constraints. The idea is to get a linear list for a given circle and set the starting pointer to where it should be after rotating N times instead of rotating each circle N times.

    def rotate(matrix: list[list[int]], count: int):
        m = len(matrix)
        n = len(matrix[0])
    
        # given circle 
        for r in range(min(m, n) // 2):
            max_x = n - r - 1
            max_y = m - r - 1
            # flattening the circle
            circle = (
                # top
                [matrix[r][i] for i in range(r, max_x + 1)] +
                # right
                [matrix[y][max_x] for y in range(r + 1, max_y)] +
                # bottom
                [matrix[max_y][i] for i in range(max_x, r - 1, -1)] + 
                # left
                [matrix[y][r] for y in range(max_y - 1, r, -1)]
            )
            length = len(circle)
            pointer = count % length
            idx = pointer
            
            # top
            for i in range(r, max_x + 1):    
                matrix[r][i] = circle[idx]
                idx = idx + 1 if idx < length - 1 else 0
            
            # right
            for i in range(r + 1, max_y):            
                matrix[i][max_x] = circle[idx]
                idx = idx + 1 if idx < length - 1 else 0
            
            # bottom   
            for i in range(max_x + 1, r, -1):            
                matrix[max_y][i - 1] = circle[idx]
                idx = idx + 1 if idx < length - 1 else 0
            
            # left
            for i in range(max_y, r + 1, -1):            
                matrix[i - 1][r] = circle[idx]
                idx = idx + 1 if idx < length - 1 else 0
        
    
    def matrixRotation(matrix, r):    
        rotate(matrix, r)
    
        for row in matrix:
            print(*row)
    
  • + 0 comments

    Here is the solution in Javascript

    /** * Complete the matrixRotation function below. * @param {number[][]} matrix - 2D array of integers * @param {number} r - rotation factor */ function matrixRotation(matrix, r) { const m = matrix.length; // Number of rows const n = matrix[0].length; // Number of columns

    // If matrix is empty or has only one element, no rotation needed
    if (m === 0 || n === 0 || (m === 1 && n === 1)) {
        printMatrix(matrix);
        return;
    }
    
    // Calculate the number of "rings" in the matrix
    const numRings = Math.min(m, n) / 2;
    
    // For each ring
    for (let ring = 0; ring < numRings; ring++) {
        // Calculate the dimensions of current ring
        const rowStart = ring;
        const rowEnd = m - 1 - ring;
        const colStart = ring;
        const colEnd = n - 1 - ring;
    
        // Calculate the number of elements in this ring
        const ringSize = 2 * (rowEnd - rowStart + colEnd - colStart);
    
        // Extract the ring elements into a 1D array
        const ringElements = [];
    
        // Top row (left to right)
        for (let j = colStart; j < colEnd; j++) {
            ringElements.push(matrix[rowStart][j]);
        }
    
        // Right column (top to bottom)
        for (let i = rowStart; i < rowEnd; i++) {
            ringElements.push(matrix[i][colEnd]);
        }
    
        // Bottom row (right to left)
        for (let j = colEnd; j > colStart; j--) {
            ringElements.push(matrix[rowEnd][j]);
        }
    
        // Left column (bottom to top)
        for (let i = rowEnd; i > rowStart; i--) {
            ringElements.push(matrix[i][colStart]);
        }
    
        // Calculate the effective number of rotations
        // For anti-clockwise rotation, we need to rotate in the opposite direction
        const effectiveRotations = r % ringElements.length;
    
        // Rotate the ring by effectiveRotations (anti-clockwise)
        const rotatedRing = [];
        for (let i = 0; i < ringElements.length; i++) {
            const newIndex = (i - effectiveRotations + ringElements.length) % ringElements.length;
            rotatedRing[i] = ringElements[newIndex];
        }
    
        // Put the rotated elements back into the matrix
        let idx = 0;
    
        // Top row (left to right)
        for (let j = colStart; j < colEnd; j++) {
            matrix[rowStart][j] = rotatedRing[idx++];
        }
    
        // Right column (top to bottom)
        for (let i = rowStart; i < rowEnd; i++) {
            matrix[i][colEnd] = rotatedRing[idx++];
        }
    
        // Bottom row (right to left)
        for (let j = colEnd; j > colStart; j--) {
            matrix[rowEnd][j] = rotatedRing[idx++];
        }
    
        // Left column (bottom to top)
        for (let i = rowEnd; i > rowStart; i--) {
            matrix[i][colStart] = rotatedRing[idx++];
        }
    }
    
    // Print the rotated matrix
    printMatrix(matrix);
    

    }

    /** * Helper function to print the matrix * @param {number[][]} matrix - 2D array of integers */ function printMatrix(matrix) { for (let i = 0; i < matrix.length; i++) { console.log(matrix[i].join(' ')); } }

    // Example usage: function main() { // Example 1 const matrix1 = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ]; console.log("Example 1 output:"); matrixRotation(matrix1, 2);

    console.log("\nExample 2 output:");
    const matrix2 = [
        [1, 2, 3, 4],
        [7, 8, 9, 10],
        [13, 14, 15, 16],
        [19, 20, 21, 22],
        [25, 26, 27, 28]
    ];
    matrixRotation(matrix2, 7);
    
    console.log("\nExample 3 output:");
    const matrix3 = [
        [1, 1],
        [1, 1]
    ];
    matrixRotation(matrix3, 3);
    

    }

    main();

    I even use this solution on my website :: https://goldprice.tr/سعر-الذهب-مباشر/

  • + 0 comments

    Python solution using dictionary:

    def matrixRotation(matrix, r):
        m = len(matrix)
        n = len(matrix[0])
        d = dict() # storing matrix coordinates and their values
        for i in range(min(m, n) // 2):
            # storing the coordinates for each loop or layer of the matrix
            loop = [(i, j) for j in range(i, n - i)] # top side
            loop += [(j, n - i - 1) for j in range(i + 1, m - i)] # right side
            loop += [(m - i - 1, j) for j in range(n - i - 2, i - 1 , -1)] # bottom side
            loop += [(j, i) for j in range(m - i - 2, i , -1)] # left side
            # listing the values of each loop of the matrix, then shift to mimic the effect of rotation
            loop_values = [matrix[r][c] for r, c in loop]
            rotated_values = loop_values[r % len(loop_values):] + loop_values[: r % len(loop_values)]
            # storing the new values of every position of the loop to respective coordinates
            for k in range(len(loop)):
                d[loop[k]] = rotated_values[k]
        # print out the resultant matrix
        for r in range(m):
            line = [d[(r, c)] for c in range(n)]
            print(*line)
    
  • + 1 comment

    Perl:

    sub rotate_matrix {
        my ($matrix, $r) = @_;
        my $rows = scalar @$matrix;
        my $cols = scalar @{$matrix->[0]};
        
        my $num_layers = int(min($rows, $cols) / 2);
        
        for my $layer (0 .. $num_layers - 1) {
            my @ring = extract_ring($matrix, $layer, $rows, $cols);
            my $perimeter = scalar @ring;
    
            my $effective_r = $r % $perimeter;
            @ring = (@ring[$effective_r .. $#ring], @ring[0 .. $effective_r - 1]);
            
            place_ring($matrix, \@ring, $layer, $rows, $cols);
        }
    }
    
    sub extract_ring {
        my ($matrix, $layer, $rows, $cols) = @_;
        my @ring;
    
        for my $i ($layer .. $cols - $layer - 1) {
            push @ring, $matrix->[$layer][$i];
        }
    
        for my $i ($layer + 1 .. $rows - $layer - 1) {
            push @ring, $matrix->[$i][$cols - $layer - 1];
        }
    
        for my $i (reverse $layer .. $cols - $layer - 2) {
            push @ring, $matrix->[$rows - $layer - 1][$i];
        }
    
        for my $i (reverse $layer + 1 .. $rows - $layer - 2) {
            push @ring, $matrix->[$i][$layer];
        }
    
        return @ring;
    }
    
    sub place_ring {
        my ($matrix, $ring_ref, $layer, $rows, $cols) = @_;
        my @ring = @$ring_ref;
        my $index = 0;
    
        for my $i ($layer .. $cols - $layer - 1) {
            $matrix->[$layer][$i] = $ring[$index++];
        }
    
        for my $i ($layer + 1 .. $rows - $layer - 1) {
            $matrix->[$i][$cols - $layer - 1] = $ring[$index++];
        }
    
        for my $i (reverse $layer .. $cols - $layer - 2) {
            $matrix->[$rows - $layer - 1][$i] = $ring[$index++];
        }
    
        for my $i (reverse $layer + 1 .. $rows - $layer - 2) {
            $matrix->[$i][$layer] = $ring[$index++];
        }
    }
    
    sub matrixRotation {
        my ($matrix, $r) = @_;
        
        rotate_matrix($matrix, $r);    
        foreach my $row (@$matrix) {
            print "@$row\n";
        }
    }
    
    sub min {
        return $_[0] < $_[1] ? $_[0] : $_[1];
    }
    
    • + 1 comment

      not working

      • + 0 comments

        On my side everything working fine.

  • + 0 comments

    C++

    void matrixRotation(vector<vector<int>> matrix, int r) {
        int mr = matrix.size();
        int mc = matrix[0].size();
        int dirx[4] = {0, 1, 0, -1}; // x, y
        int diry[4] = {1, 0, -1, 0};
        vector<vector<int>>ring; // drul
        int num_ring = min(ceil(mr / 2), ceil(mc / 2));
        for(int i = 0; i < num_ring; i++){
            int sx = i, sy = i;
            int dir = 0, current_ring_num = 2 * mc + 2 * mr - 8 * i - 4;
            vector<int> tmp;
            for(int j = 0; j < current_ring_num; j++){
                if(sx + dirx[dir] >= mc - i || sy + diry[dir] >= mr - i || sy + diry[dir] < i){
                    dir++;
                }
                tmp.push_back(matrix[sy][sx]);
                sx += dirx[dir];
                sy += diry[dir];
            }
            rotate(tmp.begin(), tmp.end() - r % current_ring_num, tmp.end());
            ring.push_back(tmp);
        }
        for(int i = 0; i < ring.size(); i++){
            int sx = i, sy = i;
            int dir = 0, current_ring_num = 2 * mc + 2 * mr - 8 * i - 4;
            for(int j = 0; j < current_ring_num; j++){
                if(sx + dirx[dir] >= mc - i || sy + diry[dir] >= mr - i || sy + diry[dir] < i){
                    dir++;
                }
                matrix[sy][sx] = ring[i][j];
                sx += dirx[dir];
                sy += diry[dir];
            }
        }
        for(int i = 0; i < matrix.size(); i++){
            for(int j = 0; j < matrix[i].size(); j++)
                cout<<matrix[i][j]<<" ";
            cout<<endl;
        }
    }