javascript – Rotate an N matrix by N by 90 degrees clockwise

With an N by N die, rotate it 90 degrees clockwise.

For example, given the following matrix:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]you should return:

[[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Follow up: What if you could not use any extra space?

``````const mtx = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
``````

My imperative solution:

``````transpose function (matrix) {
const size = matrix.length;
const newMatrix = JSON.parse (JSON.stringify (matrix));
for (let rowIndex = 0; rowIndex <size; rowIndex ++) {
line of const = matrix[rowIndex];
for (let colIndex = 0; colIndex <size; colIndex ++) {
const newRowIndex = colIndex;
const newColIndex = size - 1 - rowIndex;
newMatrix[newRowIndex][newColIndex]    = row[colIndex];
}
}
return newMatrix;
};

console.log (transpose (mtx));
``````

My declarative solution:

``````const transpose2 = matrix => {
const size = matrix.length;
const newMatrix = JSON.parse (JSON.stringify (matrix));
matrix.forEach ((row, rowIndex) => {
row.forEach ((val, colIndex) => {
const newRowIndex = colIndex;
const newColIndex = size - 1 - rowIndex;
newMatrix[newRowIndex][newColIndex]    = val;
});
});
return newMatrix;
};

console.log (transpose2 (mtx));
``````

My solution to the follow-up question:

I did not really understand the part with "no extra space". The only solution that came to my mind was to overwrite the existing matrix with the new values ​​and, at the end, clean it by removing the old values. … but adding new values ​​to old values ​​requires more space, is not it?

``````const transposeNoSpace = matrix => {
const size = matrix.length;
matrix.forEach ((row, rowIndex) => {
row.forEach ((val, colIndex) => {
const newRowIndex = colIndex;
const newColIndex = size - 1 - rowIndex;
const newVal = val ? val : val;
matrix[newRowIndex][newColIndex]    =[matrix[matrix[matrice[matrix[newRowIndex][newColIndex], newVal];
});
});
returns matrix.map (row => row.map (col => col)));
};

console.log (transposeNoSpace (mtx));
``````

I would also be interested in a pure functional solution

Posted on