

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Square matrix rotation in JavaScript
We are required to write a JavaScript function that takes in an array of arrays of n * n order (square matrix). The function should rotate the array by 90 degrees (clockwise). The condition is that we have to do this in place (without allocating any extra array).
For example −
If the input array is −
const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
Then the rotated array should look like −
const output = [ [7, 4, 1], [8, 5, 2], [9, 6, 3], ];
Example
Following is the code −
const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; const rotateArray = (arr = []) => { for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) { for (let columnIndex = rowIndex + 1; columnIndex < arr.length; columnIndex += 1) { [ arr[columnIndex][rowIndex], arr[rowIndex][columnIndex], ] = [ arr[rowIndex][columnIndex], arr[columnIndex][rowIndex], ]; } } for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) { for (let columnIndex = 0; columnIndex < arr.length / 2; columnIndex += 1) { [ arr[rowIndex][arr.length - columnIndex - 1], arr[rowIndex][columnIndex], ] = [ arr[rowIndex][columnIndex], arr[rowIndex][arr.length - columnIndex - 1], ]; } } }; rotateArray(arr); console.log(arr);
Output
Following is the output on console −
[ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]
- Related Questions & Answers
- Spiraling the elements of a square matrix JavaScript
- How to multiply single row matrix and a square matrix in R?
- A square matrix as sum of symmetric and skew-symmetric matrix ?
- Maximum and Minimum in a square matrix in C++
- Finding the rotation of an array in JavaScript
- Balancing square brackets in JavaScript
- Check given matrix is magic square or not in C++
- Difference between sum of square and square of sum in JavaScript
- Finding determinant of a square matrix using SciPy library
- Finding inverse of a square matrix using SciPy library
- Check for perfect square in JavaScript
- Positive integer square array JavaScript
- Find Maximum side length of square in a Matrix in C++
- Program to rotate square matrix by 90 degrees counterclockwise in Python
- Find smallest and largest element from square matrix diagonals in C++
Advertisements