Header Ad

HackerRank Matrix Layer Rotation problem solution

In this HackerRank Matrix Layer Rotation problem, You are given a 2D matrix of dimension m x n and a positive integer r. You have to rotate the matrix r times and print the resultant matrix. Rotation should be in the anti-clockwise direction.

HackerRank Matrix Layer Rotation problem solution


Problem solution in Python programming.

M, N, R = map(int, input().split())
mx, my = [], []

for i in range(M):
    mx.append([int(x) for x in input().split()])

for k in range(min(M, N) // 2):
    tmp = []
    i = j = k
    m, n = M - k, N - k
    while i < m - 1:
        tmp.append(mx[i][j])
        i += 1
    while j < n - 1:
        tmp.append(mx[i][j])
        j += 1
    while i > k:
        tmp.append(mx[i][j])
        i -= 1
    while j > k:
        tmp.append(mx[i][j])
        j -= 1
    my.append(tmp[-(R % len(tmp)):] + tmp[:-(R % len(tmp))])

for k in range(len(my)):
    tmp = []
    c = 0
    i = j = k
    m, n = M - k, N - k
    while i < m - 1:
        mx[i][j] = my[k][c]
        i += 1
        c += 1
    while j < n - 1:
        mx[i][j] = my[k][c]
        j += 1
        c += 1
    while i > k:
        mx[i][j] = my[k][c]
        i -= 1
        c += 1
    while j > k:
        mx[i][j] = my[k][c]
        j -= 1
        c += 1

[print(' '.join([str(b) for b in a])) for a in mx]


Problem solution in Java Programming.

import java.io.*;
import java.util.*;

public class Solution {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int m = sc.nextInt();
        int n = sc.nextInt();
        int r = sc.nextInt();
        
        int total_len = m * n;
        
        int matrix[] = new int[total_len + n];
        
        int nr_row = 0, nr_col, level = 0;
        
        for (int i = 0; i < m; i++) {
            
            nr_row = i * 2 < m ? nr_row + 1 : i * 2 == m ? i : nr_row - 1;
            nr_col = 0;
            
            for (int j = 0; j < n; j++) {
                
                nr_col = j * 2 < n ? nr_col + 1 : j * 2 == n ? j : nr_col - 1;
                
                int nr = sc.nextInt();
                
                int new_row = i, new_col = j;
                
                level = Math.min(nr_row, nr_col) - 1;
                
                int rotations = r % ((2 * ((m + n) - 4 * level)) - (m > 2 && n > 2 ? 4 : 0));
                
                for (int k = 0; k < rotations; k++) {
                    
                    if (new_row == level) {
                        if (new_col > level ) {
                            new_col -= 1;
                        } else {
                            new_row += 1;
                        }
                    } else if (new_row == m - level - 1) {
                        if (new_col < n - level - 1) {
                            new_col += 1;
                        } else {
                            new_row -= 1;
                        }
                    } else if (new_col == level) {
                        if (new_row < m - 1) {
                            new_row += 1; 
                        } else {
                            new_col += 1;
                        }
                    } else if (new_col == n - level - 1) {
                        if (new_row > 0) {
                            new_row -= 1;
                        } else {
                            new_col -= 1;
                        }
                    }    
                }      
                
                matrix[new_row * n + new_col] = nr;
            }
            
        }
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(matrix[i * n + j] + " ");
            }
            System.out.println();
        }
        
    }
}


Problem solution in C++ programming.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int W,H,R;
    cin>>H>>W>>R;
    int ncycles=min(W,H)/2;
    int m[W*H];
    int cycles[150][1196];
    int i,x,y;
    int cycle,cyclelen;
    for(i=0;i<W*H;i++)cin>>m[i];
    for(cycle=0;cycle<ncycles;cycle++){
        i=0;
        x=y=cycle;
        for(;y<H-cycle-1;y++)cycles[cycle][i++]=m[W*y+x];
        for(;x<W-cycle-1;x++)cycles[cycle][i++]=m[W*y+x];
        for(;y>cycle;y--)cycles[cycle][i++]=m[W*y+x];
        for(;x>cycle;x--)cycles[cycle][i++]=m[W*y+x];
    }
    for(cycle=0;cycle<ncycles;cycle++){
        cyclelen=2*(W-2*cycle)+2*(H-2*cycle)-4;
        i=-R%cyclelen+cyclelen;
        x=y=cycle;
        for(;y<H-cycle-1;y++)m[W*y+x]=cycles[cycle][i++%cyclelen];
        for(;x<W-cycle-1;x++)m[W*y+x]=cycles[cycle][i++%cyclelen];
        for(;y>cycle;y--)m[W*y+x]=cycles[cycle][i++%cyclelen];
        for(;x>cycle;x--)m[W*y+x]=cycles[cycle][i++%cyclelen];
    }
    for(y=0;y<H;y++){
        for(x=0;x<W;x++){
            if(x)cout<<' ';
            cout<<m[W*y+x];
        }
        cout<<endl;
    }
    return 0;
}


Problem solution in C programming.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int** matrix;

void init(int rows, int cols) {
	matrix = malloc( sizeof( int*) * rows);
	
	for (int row = 0; row < rows; row++) {
		*(matrix + row) = malloc( sizeof(int) * cols);
	}

	//Load Matrices
	int scan_var = -1;
	for (int row = 0; row < rows; row++) {
		for (int col = 0; col< cols; col++) {
				
			scanf("%d ", &scan_var);
			matrix[row][col] = scan_var;
		}
	}//end loading
}

void print(int** matrix, int rows, int cols) {
	for (int row = 0; row < rows; row++) {
		for (int col = 0; col< cols; col++) {
			printf("%d ", matrix[row][col]);
		}
		printf("\n");
	}
}

void rotate(int** matrix, int top, int bottom, int left, int right) {
	int temp;
	
	temp = matrix[bottom][right];

	//Bottom Row of matrix
	for (int i = right; i >= left + 1; i--)
		matrix[bottom][i] = matrix[bottom][i-1];
	
	//Left Column of matrix
	for (int i = bottom; i >= top + 1; i--)
		matrix[i][left] = matrix[i-1][left];

	//Top Row of matrix
	for (int i = left; i <= right - 1; i++)
		matrix[top][i] = matrix[top][i+1];

	//Right Column of matrix
	for (int i = top; i <= bottom - 1; i++)
		matrix[i][right] = matrix[i+1][right];

	matrix[bottom - 1][right] = temp;
}

int main(int argc, char* argv[]) {
	
	int rows, cols, r;
	scanf("%d %d %d\n", &rows, &cols, &r);			
	
	init(rows, cols);
	
	/*int rotations = 0;
	for (int rotations = 0; rotations < r; rotations++) {
		//rotate the entire matrix one "square" at a time
		//moving in from outermost square
		int i = 0;

		while( i < (rows - 1 - i) && i < (cols - i - 1)) {
			rotate(matrix, 0 + i, rows - i - 1, 0 + i, cols - 1 - i);
			i++;
		}
	}*/

	int i = 0;
	int items_per_row, items_per_col, total_items, actual_rotations;
	while( i < (rows - i - 1) && i < (cols - i - 1)) {
		items_per_row = cols - (2 * i);
		items_per_col = rows - (2 * i) - 2; //subtract 2 for items in row
		total_items = items_per_row * 2 + items_per_col * 2;

		actual_rotations = r % total_items;

		for (int rotations = 0; rotations < actual_rotations; rotations++) {
			rotate(matrix, 0 + i, rows - i - 1, 0 + i, cols - 1 - i);
		}
		i++;
	}

	print(matrix, rows, cols);

	return 0;
}


Problem solution in JavaScript programming.

function valueAt(matrix, x, y, rot) {
    var level, limits = { x:0, y:0 }, levels = { x: 0, y: 0};
    levels.x = (x < matrix[y].length/2) ? x : matrix[y].length - x - 1;
    levels.y = (y < matrix.length/2) ? y : matrix.length - y - 1;
    level = Math.min(levels.x, levels.y);
    limits.x = matrix[y].length-level-1;
    limits.y = matrix.length-level-1;
    
    var max = (matrix.length-level*2)*2 + (matrix[y].length-level*2)*2 - 4;
    //process.stdout.write("\n! " + max + " : " + rot + " -x " + limits.x + " -y " + limits.y + "\n");

    rot = rot % max;
    
    
    for (; rot > 0; rot--)
        if (y == level && x < limits.x) x += 1;
        else if (x == limits.x && y < limits.y) y += 1;
        else if (y == limits.y && x > level) x -= 1;
        else if (x == level && y > level) y-=1;
    
    return matrix[y][x];
}

function processData(input) {
    var numbers, lines = input.split("\n");
    var dims = lines[0].split(' ').map(function(v) { return parseInt(v); });
    var rows = dims[0];
    var cols = dims[1];
    var rots = dims[2];
    var matrix = [];
    for (var y = 0; y < lines.length-1; y++) {
        numbers = lines[y+1].split(' ');
        matrix.push(numbers);
        //for (var x = 0; x < numbers.length; )
    }
    
    for (var y = 0; y < matrix.length; y++) {
        for (var x = 0; x < matrix[y].length; x++)
            process.stdout.write(valueAt(matrix, x, y, rots) + " ");
        process.stdout.write("\n");
    }
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});


Post a Comment

0 Comments