Sort by

recency

|

778 Discussions

|

  • + 0 comments

    They called me a mad man. Single pass, 1 nested loop, let's goooooooooo!

    So, what we are doing, since we already have the matrix, is calculating the location of the number from the original matrix that should fall on the position we are currently printing. So, instead of transforming the matrix, we are kind of going in the oposite directioin and figuring out what number would be where in the final matrix rather than transforming it.

    (The amount of times those ifs were tweaked is not up for discussion.)

    Also, do beware, this is not a pretty sight.

    void matrixRotation(vector<vector<int>> matrix, int r) {
        int row = matrix.size(), col = matrix[0].size();
        
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                
                int layer = min({i, j, row-1-i, col-1-j});
                
                int top = layer, left = layer;
                int bottom = row-1-layer, right = col-1-layer;
                
                int perimeter = 2 * ((bottom-top) + (right-left));
                
                int idx = 0;
                if (i == top){ 
                    idx = j-left;
                }else if (j == right){
                    idx = (right-left) + (i-top);
                }else if (i == bottom){ 
                    idx = (right-left) + (bottom-top) + (right-j);
                }else{ 
                    idx = (right-left) + (bottom-top) + (right-left) + (bottom-i);
                }
                
                int newIdx = (idx + r) % perimeter;
                
                int x, y;
                if (newIdx < (right-left)){ 
                    x = top; 
                    y = left + newIdx; 
                }else if (newIdx < (right-left) + (bottom-top)){ 
                    x = top + (newIdx - (right-left)); 
                    y = right; 
                }else if (newIdx < (right-left)*2 + (bottom-top)){ 
                    x = bottom; 
                    y = right - (newIdx - ((right-left)+(bottom-top))); 
                }else{ 
                    x = bottom - (newIdx - ((right-left)*2 + (bottom-top))); 
                    y = left; 
                }
                
                cout << matrix[x][y] << " ";
            }
            cout << endl;
        }
    }
    
  • + 1 comment

    One of the idea is by extracting to straps, rotate it, and combine it back as a matrix.

    For the last one, combining it back is quite tedious, so I personally prefer to utilize classes (in-place assignments / reference-assignment) so that I dont need to deal the last one (combine it back)

    For the strap example, it should be: matrix (height=5, width=4):

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

    There will be 2 straps: [1, 5, 9, 13, 17, 18, 19, 20, 16, 12, 8, 4, 3, 2] and the second one: [6, 10, 14, 15, 11, 7, ]

    class Value():
        def __init__(self, val):
            self.val = val
        
        def set(self, new_val):
            self.val = new_val
            
        def __str__(self):
            return str(f"{self.val}")
    
        def __repr__(self):
            return str(f"{self.val:2d}")
    
    
    def matrixRotation(matrix, r):
        h = len(matrix)
        w = len(matrix[0])
        
        matrix = [   # convert to reference-based values
            [
                Value(col)
                for col in row
            ]
            for row in matrix
        ]
        # max number of straps. indexes means strap
        num_of_indexes = min(h,w) // 2  
    
        for index in range(num_of_indexes):
            extracted = extract(matrix, index)
            extracted_render = [x.val for x in extracted]
            r_mod = r % len(extracted_render)
            for i in range(len(extracted)):
                extracted[i].val = extracted_render[i-r_mod]
    						
    		# combine back process. But because we use classes/references, 
    		# dont need to do extra complex things here. Just print as usual
        for row in matrix:
            print(" ".join(map(str, row)))
            
        
    
    def extract(matrix, dia_index):  # extract strap arrays by strap-index 
        h = len(matrix)
        w = len(matrix[0])
        ret = []
        for y in range(dia_index+0, h-dia_index):  # from top-left to bottom
            ret.append(matrix[y][dia_index])
        for x in range(dia_index+1, w-dia_index):  # from bottom-left to right (except the first item, already included by for-loop above)
            ret.append(matrix[-dia_index-1][x])
        for y in range(h-1 - 1 - dia_index, dia_index - 1, -1):  # from bottom-right to top (except the first item)
            ret.append(matrix[y][-dia_index-1])
        for x in range(w-1 - 1 - dia_index, dia_index, -1):  # from top-right to left   (except first and last item)
            ret.append(matrix[dia_index][x])
        return ret
        
    
  • + 0 comments

    Javascript

    function matrixRotation(matrix, r) {
        // Write your code here
        const rows = matrix.length;
        const cols = matrix[0].length;
        const buffer = new Array((rows + cols - 2) * 2);
        const m_action_walk = (i, s, bs, mx, my) => {
            buffer[(i + s) % bs] = matrix[my][mx];
        };
        const m_action_write = (i, s, bs, mx, my) => {
            matrix[my][mx] = buffer[(i + s) % bs];
        };
        const walk_matrix_around = (x, y, action, s) => {
            let i = 0;
            let bsize = (rows - 2 * x + cols - 2 * y) * 2 - 4;
            for (let row = y; row < rows - y; row++)
                action(i++, s, bsize, x, row);
            for (let col = x + 1; col < cols - x; col++)
                action(i++, s, bsize, col, rows - y - 1);
            for (let row = rows - y - 2; row >= y; row--)
                action(i++, s, bsize, cols - x - 1, row);
            for (let col = cols - x - 2; col > x; col--)
                action(i++, s, bsize, col, y);
        };
        for(let xy = 0; xy < rows - xy && xy < cols - xy; xy++) {
            walk_matrix_around(xy, xy, m_action_walk, r);
            walk_matrix_around(xy, xy, m_action_write, 0);
        }
        for (let row = 0; row < rows; row++) {
            console.log(matrix[row].join(' '));
        }
    }
    
  • + 0 comments

    hello everyone

    this is my java sol and this it is passing all the tese cases. can anyone give me the suggetion to improve my code public static void printMatrix(List> matrix){ for(int i=0;i> matrix, int r) { // Write your code here int row = matrix.size(); int col = matrix.get(0).size();

    for(int k=0;k<Math.min(row, col)/2;k++){
    int totalElement = (2*(row-2*k) + 2*(col-2*k))-4;
    // System.out.println("total "+totalElement);
    int it=r%totalElement;
    int i=0+k, j=0+k;
    
    while(it>0){
    
        int[] tempb = new int[row];
        tempb[i] = matrix.get(i).get(j);
        while(i<row-1-k){
            tempb[i+1] = matrix.get(i+1).get(j);
            matrix.get(i+1).set(j, tempb[i]);
            i++; 
        }
    
        int[] tempr = new int[col];
        tempr[0] = tempb[i];
        int index=0;
        while(j<col-1-k){
            tempr[index+1] = matrix.get(i).get(j+1);
            matrix.get(i).set(j+1, tempr[index]);
            j++;
            index++;
        }
    
        int[] tempup = new int[row];
        tempup[0] = tempr[index];
        index=0;
        while(i>=1+k){
            tempup[index+1] = matrix.get(i-1).get(j);
            matrix.get(i-1).set(j, tempup[index]);
            i--;
            index++;
        }
    
        int[] templ = new int[col];
        templ[0] = tempup[index];
        index=0;
        while(j>=1+k){
            templ[index+1] = matrix.get(i).get(j-1);
            matrix.get(i).set(j-1, templ[index]);
            j--;
            index++;
        }
        it--;
    }    
        }
    
    printMatrix(matrix);
    }
    

    }

  • + 0 comments

    Last 2 for loops were for debugging, you only need the second one for the actual solution, and GrowthMount can help optimize this process.