- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- Spiraling the elements of a square matrix JavaScript
- Finding the rotation of an array in JavaScript
- How to multiply single row matrix and a square matrix in R?
- Maximum and Minimum in a square matrix in C++
- A square matrix as sum of symmetric and skew-symmetric matrix ?
- Check given matrix is magic square or not in C++
- Find Maximum side length of square in a Matrix in C++
- Check if matrix can be converted to another matrix by transposing square sub-matrices in Python
- Find smallest and largest element from square matrix diagonals in C++
- Program to rotate square matrix by 90 degrees counterclockwise in Python
- Finding determinant of a square matrix using SciPy library
- Finding inverse of a square matrix using SciPy library
- Check for perfect square in JavaScript
- Difference between sum of square and square of sum in JavaScript
- Algorithm for matrix multiplication in JavaScript

Advertisements