- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 ] ]
Advertisements