HackerRank Matrix Layer Rotation Solution Yashwant Parihar, April 22, 2023April 28, 2023 In this post, we will solve HackerRank Matrix Layer Rotation Problem Solution. 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 anti-clockwise direction.Rotation of a 4×5 matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only. It is guaranteed that the minimum of m and n will be even. As an example rotate the Start matrix by 2: Start First Second 1 2 3 4 2 3 4 5 3 4 5 6 12 1 2 5 -> 1 2 3 6 -> 2 3 4 7 11 4 3 6 12 1 4 7 1 2 1 8 10 9 8 7 11 10 9 8 12 11 10 9 Function Description Complete the matrixRotation function in the editor below. matrixRotation has the following parameter(s): int matrix[m][n]: a 2D array of integers int r: the rotation factor PrintsIt should print the resultant 2D integer array and return nothing. Print each row on a separate line as space-separated integers. Input FormatThe first line contains three space separated integers, m. n. and r, the number of rows andcolumns in matrix, and the required rotation.The next m lines contain n space-separated integers representing the elements of a row ofmatrix. Sample Input Sample Input #01 STDIN Function ----- -------- 4 4 2 rows m = 4, columns n = 4, rotation factor r = 2 1 2 3 4 matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] 5 6 7 8 9 10 11 12 13 14 15 16 Sample Output #01 3 4 8 12 2 11 10 16 1 7 6 15 5 9 13 14 Explanation #01 The matrix is rotated through two rotations. 1 2 3 4 2 3 4 8 3 4 8 12 5 6 7 8 1 7 11 12 2 11 10 16 9 10 11 12 -> 5 6 10 16 -> 1 7 6 15 13 14 15 16 9 13 14 15 5 9 13 14 Sample Input #02 5 4 7 1 2 3 4 7 8 9 10 13 14 15 16 19 20 21 22 25 26 27 28 Sample Output #02 28 27 26 25 22 9 15 19 16 8 21 13 10 14 20 7 4 3 2 1 Explanation 02 The various states through 7 rotations: 1 2 3 4 2 3 4 10 3 4 10 16 4 10 16 22 7 8 9 10 1 9 15 16 2 15 21 22 3 21 20 28 13 14 15 16 -> 7 8 21 22 -> 1 9 20 28 -> 2 15 14 27 -> 19 20 21 22 13 14 20 28 7 8 14 27 1 9 8 26 25 26 27 28 19 25 26 27 13 19 25 26 7 13 19 25 10 16 22 28 16 22 28 27 22 28 27 26 28 27 26 25 4 20 14 27 10 14 8 26 16 8 9 25 22 9 15 19 3 21 8 26 -> 4 20 9 25 -> 10 14 15 19 -> 16 8 21 13 2 15 9 25 3 21 15 19 4 20 21 13 10 14 20 7 1 7 13 19 2 1 7 13 3 2 1 7 4 3 2 1 Sample Input #03 2 2 3 1 1 1 1 Sample Output #03 1 1 1 1 Explanation #03 All of the elements are the same, so any rotation will repeat the same matrix. HackerRank Matrix Layer Rotation Problem Solution Matrix Layer Rotation C Solution #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int row,col,rot; int i,j,current; int rIndex,cIndex; int min1,min2,frameNumber; int horRot,verRot,currentRot; int rotmat[300][300]; scanf("%d %d %d",&row,&col,&rot); for(i=0;i<row;i++) { for(j=0;j<col;j++) { scanf("%d",¤t); min1=fmin(i,j); min2=fmin(col-1-j,row-1-i); frameNumber=fmin(min1,min2); horRot=col-1-2*frameNumber; verRot=row-1-2*frameNumber; currentRot=rot%(2*(horRot+verRot)); rIndex=i; cIndex=j; while(currentRot!=0) { if(rIndex==frameNumber && cIndex>frameNumber) { cIndex--; } else if(cIndex==frameNumber && rIndex<(row-1-frameNumber)) { rIndex++; } else if(rIndex==(row-1-frameNumber) && cIndex<(col-1-frameNumber)) { cIndex++; } else if(cIndex==(col-1-frameNumber) && rIndex>frameNumber) { rIndex--; } currentRot--; } rotmat[rIndex][cIndex]=current; } } for(i=0;i<row;i++) { for(j=0;j<col;j++) { printf("%d ",rotmat[i][j]); } printf("\n"); } return 0; } Matrix Layer Rotation C++ Solution #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int M,N,R; cin >> M >> N >> R; vector<vector<int>> v(M, vector<int>(N,0)); for(auto&r:v) for(auto&c:r) cin >> c; int nlayer = min(N,M)/2; for (int i=0; i < nlayer; ++i) { // cerr << "layer#"<<i<<endl; vector<int*> layer; int nrows = M-2*i; int ncols = N-2*i; // cerr << "nrows="<<nrows << endl << "ncols="<<ncols<<endl; for (int c=i; c < N-i-1; ++c) layer.push_back(&v[i][c]); // top // for (auto i:layer) cerr << *i <<" ";cerr<<endl; for (int r=i; r < M-1-i; ++r) layer.push_back(&v[r][N-1-i]); // right //for (auto i:layer) cerr <<*i <<" ";cerr<<endl; for (int c=i; c < N-i-1; ++c) layer.push_back(&v[M-1-i][N-1-c]); // bottom // for (auto i:layer) cerr <<*i <<" ";cerr<<endl; for (int r=i; r < M-1-i; ++r) layer.push_back(&v[M-1-r][i]); // left //for (auto i:layer) cerr <<*i <<" ";cerr<<endl; vector<int> l(layer.size()); transform(layer.begin(),layer.end(),l.begin(),[](auto p){return*p;}); int r = R % (l.size()); rotate(l.begin(), l.begin()+r, l.end()); //for (int i:l) cerr << i << " "; cerr << endl; for (size_t i=0; i < l.size(); ++i) { *layer[i] = l[i]; } // cerr<<endl; } for(auto&r:v) { for(auto&c:r) cout << c << " "; cout << endl; } return 0; } Matrix Layer Rotation C Sharp Solution using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class MatrixRotation { public Int32 RowNumber { get; set; } public Int32 ColumnNumber { get; set;} public Int32 RotationNumer { get; set; } public Int32[,] Matrix; public Int32[,] Matrix_Rotation; /// <summary> /// cross line position, [0,0],[1,1]...[n,n] /// </summary> public List<Tuple<Int32,Int32>> DiagonalNumber { get; set; } public void PrintMatrix(Int32[,] matrix) { Int32 lengthX = matrix.GetLength(1); Int32 lengthY = matrix.GetLength(0); for (Int32 y = 0; y < lengthY; y++) { for (Int32 x = 0; x < lengthX; x++) { if(x==lengthX-1) Console.Write(matrix[y, x]); else { Console.Write(matrix[y, x] + " "); } } Console.WriteLine(); } } public Int32[,] RotateRight(Int32[,] matrix) { Int32 lengthY = matrix.GetLength(0); Int32 lengthX = matrix.GetLength(1); Int32[,] result = new Int32[lengthX, lengthY]; for (Int32 y = 0; y < lengthY; y++) for (Int32 x = 0; x < lengthX; x++) result[x, y] = matrix[lengthY - 1 - y, x]; return result; } public void Test() { TestRotation(new Int32[4, 4] { { 1, 2,3,4 }, { 5,6,7,8 }, { 9,10,11,12 },{13,14,15,16} }); Console.WriteLine(); TestRotation(new Int32[2, 3] { { 0, 1, 2 }, { 3, 4, 5 } }); } public void TestRotation(Int32[,] matrix) { Console.WriteLine("the original matrix:"); PrintMatrix(matrix); Console.WriteLine(); Console.WriteLine("the right rotated matrix:"); PrintMatrix(RotateRight(matrix)); Console.WriteLine(); //Console.WriteLine("the left rotated matrix:"); //PrInt32Matrix(RotateLeft(matrix)); } public void CreateEmptyMatrix() { Matrix=new Int32[RowNumber,ColumnNumber]; Matrix_Rotation=new Int32[RowNumber,ColumnNumber]; } public void CreateMatrix(Int32 rowIdx, string s) { string[] rowStringList = s.Split(' '); for (Int32 i = 0; i < ColumnNumber; i++) { Matrix[rowIdx, i] = Convert.ToInt32(rowStringList[i]); Matrix_Rotation[rowIdx, i] = Convert.ToInt32(rowStringList[i]); } } public void PrintMatrixRotation() { if (Matrix.Length > 0 && RowNumber > 0 && ColumnNumber > 0) { DiagonalNumber = new List<Tuple<Int32, Int32>>(); // calculate the each rotation index // for example // row =10, colunn =10 // first round is (row=0, column=9) // second round is (row =1, column=8) // .... etc (row = 4, column =5) for (Int32 rowIdx = 0, colIdx = 0; rowIdx < RowNumber && colIdx < ColumnNumber; rowIdx++, colIdx++) { if (DiagonalNumber.Count(x => x.Item1 == rowIdx && x.Item2 == colIdx) == 0) { DiagonalNumber.Add(new Tuple<int,int>(rowIdx,colIdx)); List<Tuple<Int32, Int32>> currentRotation = new List<Tuple<Int32, Int32>>(); int ColNumberInCurrentRoation = ColumnNumber - 2*colIdx; int RowNumberInCurrentRotation = RowNumber - 2*rowIdx; //Move Right for (Int32 col = colIdx; col <= ColumnNumber - colIdx - 1; col++) { if (col == rowIdx && DiagonalNumber.Count(x => x.Item1 == rowIdx && x.Item2 == colIdx) == 0) DiagonalNumber.Add(new Tuple<Int32, Int32>(rowIdx, col)); currentRotation.Add(new Tuple<Int32, Int32>(rowIdx, col)); } //Move Down for (Int32 row = rowIdx + 1; row <= RowNumber - rowIdx - 1; row++) { if (!currentRotation.Any(x => x.Item1 == row && x.Item2 == ColumnNumber - colIdx - 1)) { currentRotation.Add(new Tuple<Int32, Int32>(row, ColumnNumber - colIdx - 1)); if (ColumnNumber - colIdx - 1 == row && DiagonalNumber.Count(x => x.Item1 == rowIdx && x.Item2 == ColumnNumber - colIdx - 1) == 0) DiagonalNumber.Add(new Tuple<Int32, Int32>(row, ColumnNumber - colIdx - 1)); } } //Move Left for (Int32 col = ColumnNumber - colIdx - 1 - 1; col >= colIdx; col--) { if (!currentRotation.Any(x => x.Item1 == RowNumber - rowIdx - 1 && x.Item2 == col)) { currentRotation.Add(new Tuple<Int32, Int32>(RowNumber - rowIdx - 1, col)); if (RowNumber - rowIdx - 1 == col && DiagonalNumber.Count(x => x.Item1 == RowNumber - rowIdx - 1 && x.Item2 == col) == 0) DiagonalNumber.Add(new Tuple<Int32, Int32>(RowNumber - rowIdx - 1, col)); } } //Move Up for (Int32 row = RowNumber - rowIdx - 1 - 1; row >= rowIdx; row--) { if (!currentRotation.Any(x => x.Item1 == row && x.Item2 == colIdx)) { if (row == colIdx && DiagonalNumber.Count(x => x.Item1 == row && x.Item2 == colIdx)==0) { DiagonalNumber.Add(new Tuple<Int32, Int32>(row, colIdx)); } currentRotation.Add(new Tuple<Int32, Int32>(row, colIdx)); } } // shift matrix based on current rotation position list for (int shiftIdx = 0; shiftIdx < RotationNumer % ((ColNumberInCurrentRoation+RowNumberInCurrentRotation - 2) * 2); shiftIdx++) ShiftMatrix(currentRotation); } else { break; } } } //PrInt32Matrix(Matrix); //PrInt32Matrix(Matrix_Rotation); } //private void PrInt32Matrix(Int32[,] Matrix_Rotation) //{ // if (Matrix_Rotation.Length > 0) // { // for (Int32 i = 0; i < Matrix_Rotation.Length; i++) // { // for (Int32 j = 0; j < Matrix_Rotation.Rank; j++) // { // Console.Write("{0} ", Matrix_Rotation[i, j]); // } // Console.WriteLine(); // } // } //} private void ShiftMatrix(List<Tuple<Int32, Int32>> rotationList) { if (rotationList.Count > 0) { Int32 firstNumber = 0; for (Int32 i = 0; i <= rotationList.Count; i++) { if (i == 0) { Int32 item1 = rotationList[i].Item1; Int32 item2 = rotationList[i].Item2; Int32 v = Matrix_Rotation[item1, item2]; firstNumber = Matrix_Rotation[rotationList[i].Item1, rotationList[i].Item2]; } else if (i == rotationList.Count) { Int32 item1 = rotationList[i-1].Item1; Int32 item2 = rotationList[i-1].Item2; Int32 v = Matrix_Rotation[item1, item2]; Matrix_Rotation[rotationList[i-1].Item1, rotationList[i-1].Item2] = firstNumber; } else { Int32 item1 = rotationList[i].Item1; Int32 item2 = rotationList[i].Item2; Int32 v_pre = Matrix_Rotation[rotationList[i - 1].Item1, rotationList[i - 1].Item2]; Int32 v = Matrix_Rotation[rotationList[i].Item1, rotationList[i].Item2]; Matrix_Rotation[rotationList[i - 1].Item1, rotationList[i - 1].Item2] = Matrix_Rotation[rotationList[i].Item1, rotationList[i].Item2]; } } } } static void Main(string[] args) { MatrixRotation mrObjRotation = new MatrixRotation(); string input = Console.ReadLine(); string[] rowcols= input.Split(' '); int rowIdx = 0; mrObjRotation.RowNumber = Convert.ToInt32(rowcols[0]); mrObjRotation.ColumnNumber = Convert.ToInt32(rowcols[1]); mrObjRotation.RotationNumer = Convert.ToInt32(rowcols[2]); mrObjRotation.CreateEmptyMatrix(); string inputRow = Console.ReadLine(); while (!string.IsNullOrEmpty(inputRow)) { mrObjRotation.CreateMatrix(rowIdx, inputRow); inputRow = Console.ReadLine(); rowIdx++; } mrObjRotation.PrintMatrixRotation(); mrObjRotation.PrintMatrix(mrObjRotation.Matrix_Rotation); } } } Matrix Layer Rotation Java Solution import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; class Result { /* * Complete the 'matrixRotation' function below. * * The function accepts following parameters: * 1. 2D_INTEGER_ARRAY matrix * 2. INTEGER r * * * */ public static void matrixRotation(List<List<Integer>> matrix, int rotate) { List<Integer> layerone=null; int cols = matrix.get(0).size(); int rows = matrix.size(); int rows_start =0; int rows_end=rows-1; int cols_start=0; int cols_end=cols-1; // the number of layer is the min(M,N)/2 int numboflayer = matrix.size()<matrix.get(0).size()?matrix.size()/2:matrix.get(0).size()/2; List<Integer> layerone_order = null; Map<Integer,List<Integer>> mapLayers = new HashMap<>(); // create matrix layer for(int layer=0;layer<numboflayer;layer++) { layerone_order = new ArrayList<>(); layerone=new ArrayList<>(); rows_start=layer; rows_end=rows-1-layer; cols_start=layer; cols_end=cols-1-layer; layerone.addAll(matrix.get(rows_start).subList(cols_start,cols_end)); for(int r=rows_start;r<=rows_end;r++) { layerone.add(matrix.get(r).get(cols_end)); } List<Integer> tempList = new ArrayList<>(); tempList.addAll(matrix.get(rows_end).subList(cols_start,cols_end)); Collections.reverse(tempList); layerone.addAll(tempList); for(int i=rows_end-1;i>rows_start;i--) { layerone.add(matrix.get(i).get(rows_start)); } layerone_order.addAll(layerone.subList(rotate%layerone.size(),layerone.size())); layerone_order.addAll(layerone.subList(0,rotate%layerone.size())); mapLayers.put(layer,layerone_order); } // print layer matrix rotation //aprintLayers(mapLayers); int index=0; for(int layer=0;layer<numboflayer;layer++) { index=0; rows_start=layer; rows_end=rows-1-layer; cols_start=layer; cols_end=cols-1-layer; for(int col_layer=0;col_layer<=cols_end-cols_start;col_layer++) { matrix.get(rows_start).set(cols_start+col_layer,mapLayers.get(layer).get(col_layer)); } index=0; for(int row=rows_start+1;row<rows_end;row++) { index++; matrix.get(row).set(cols_start,mapLayers.get(layer).get(mapLayers.get(layer).size()-index)); matrix.get(row).set(cols_end,mapLayers.get(layer).get(cols_end-cols_start+index)); } for(int col_layer=0;col_layer<=cols_end-cols_start;col_layer++) { matrix.get(rows_end).set(cols_start+col_layer,mapLayers.get(layer).get(mapLayers.get(layer).size()-index-col_layer-1)); } } printMatrix(matrix); } private static void printLayers(Map<Integer,List<Integer>> mapLayers) { mapLayers.forEach((key,value)->{ System.out.print(" - " + key + " - "); value.stream().forEach(el->{ System.out.print(el+" "); }); }); System.out.println(""); } private static void printMatrix(List<List<Integer>> matrix) { matrix.stream().forEach(row->{ row.stream().forEach(col->{ System.out.print(col + " "); }); System.out.println(""); }); } } public class Solution { public static void main(String[] args) throws IOException { try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) { String line = bufferedReader.readLine(); //System.out.println(line); //System.out.println(line.replaceAll("\\s+$", "").split(" ")); String[] firstMultipleInput = line.replaceAll("\\s+$", "").split(" "); int m = Integer.parseInt(firstMultipleInput[0]); int n = Integer.parseInt(firstMultipleInput[1]); int r = Integer.parseInt(firstMultipleInput[2]); List<List<Integer>> matrix = new ArrayList<>(); IntStream.range(0, m).forEach(i -> { try { matrix.add( Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(Collectors.toList()) ); } catch (IOException ex) { throw new RuntimeException(ex); } }); Result.matrixRotation(matrix, r); } catch(IOException io) { throw new RuntimeException(io); } } } Matrix Layer Rotation JavaScript Solution function processData(input) { var lines = input.split('\n'); var params = lines[0].split(' ').map(Number); var numRows = params[0]; var numCols = params[1]; var numRotations = params[2]; var a = []; for(var i=0; i<numRows; i++){ var row = lines[i+1].split(' ').map(Number); a.push(row); } var sequences = readArray(a, numRows, numCols); sequences.forEach(function(sequence){ rotateSequence(sequence, numRotations); }); var result = writeArray(sequences, numRows, numCols); printResult(result); } function readArray(a, numRows, numCols){ var sequences = []; var numSequences = Math.ceil(Math.min(numRows/2, numCols/2)); for(var i=0; i<numSequences; i++){ var sequence = []; var p = { x:i, y:i }; var d = { x:0, y:1 }; var hasCompleted = false; sequence.push(a[p.y][p.x]); while(!hasCompleted){ p.x += d.x; p.y += d.y; if(p.y >= numRows-i){ d.x = 1; d.y = 0; p.x += 1; p.y -= 1; } else if(p.x >= numCols-i){ d.x = 0; d.y = -1; p.x -= 1; p.y -= 1; } else if(p.y < i){ d.x = -1; d.y = 0; p.x -= 1; p.y += 1; } if(p.x == i && p.y == i){ hasCompleted = true; } else { sequence.push(a[p.y][p.x]); } } sequences.push(sequence); } return sequences; } function rotateSequence(sequence, numRotations){ numRotations = numRotations % sequence.length; var temp = sequence.splice(sequence.length-numRotations, numRotations); sequence.unshift.apply(sequence, temp); } function writeArray(sequences, numRows, numCols){ var a = []; for(var i=0; i<numRows; i++){ a[i] = []; } sequences.forEach(function(sequence, i){ var j = 0; var p = { x:i, y:i }; var d = { x:0, y:1 }; var hasCompleted = false; a[p.y][p.x] = sequence[j]; while(!hasCompleted){ p.x += d.x; p.y += d.y; if(p.y >= numRows-i){ d.x = 1; d.y = 0; p.x += 1; p.y -= 1; } else if(p.x >= numCols-i){ d.x = 0; d.y = -1; p.x -= 1; p.y -= 1; } else if(p.y < i){ d.x = -1; d.y = 0; p.x -= 1; p.y += 1; } if(p.x == i && p.y == i){ hasCompleted = true; } else { j += 1; a[p.y][p.x] = sequence[j]; } } }); return a; } function printResult(a){ a.forEach(function(row){ console.log(row.join(' ')); }); } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); Matrix Layer Rotation Python Solution m,n,r = list( map( int, input().split() ) ) loops = int( min( m,n ) / 2 ) def roundtrip( i, m, n ): for r in range( i, m-i-1 ): yield ( r, i ) for r in range( i, n-i-1 ): yield ( m-i-1, r ) for r in range( m-i-1, i, -1 ): yield ( r, n-i-1 ) for r in range( n-i-1, i, -1 ): yield ( i, r ) posToLoop = {} loopToPos = {} loopMax = {} for l in range(loops): idx = 0 for i in roundtrip( l, m, n ): posToLoop[ i ] = ( l, idx ) loopToPos[ ( l, idx ) ] = i idx += 1 loopMax[ l ] = idx matrix = [[0 for x in range(n)] for x in range(m)] y = 0 for i in range( m ): line = input().split() x = 0 for num in line: l,p = posToLoop[ (y,x) ] p = ( p + r ) % loopMax[ l ] p = loopToPos[ (l,p) ] matrix[ p[0] ][ p[1] ] = num x += 1 y += 1 for l in matrix: print( ' '.join( l ) ) Other Solutions HackerRank Big Sorting Problem Solution HackerRank Super Reduced String Solution c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython