Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save PantherHawk/498c923ed9df9cc8c032a417aa22539a to your computer and use it in GitHub Desktop.
Save PantherHawk/498c923ed9df9cc8c032a417aa22539a to your computer and use it in GitHub Desktop.
https://repl.it/@pantherhawk22/2D-Matrix-Rotation
// rotate 2d grid 90 degrees
// o: 2d array rotated 90 degrees, counter clockwise
// i: 2d array, width = length
// c: no worse the O(n^2)
// PLAN:
// reverse order of rows
// replace the last column elements of each row with elements in the first row, until you reach the next to last
// then replace second to last
//
// [1,1,1], [3, 3, 3],
// [2,2,2], == > [2, 2, 2],
// [3,3,3] [1, 1, 1]
//
// replace first row first column with last row last column
// [3, 3, 3], [1, 3, 3],
// [2, 2, 2] === > [2, 2, 2]
// [1, 1, 1] [1, 1, 3]
// replace first row second column with second row last column
// [1, 3, 3] [1, 2, 3]
// [2, 2, 2] == > [2, 2, 3]
// [1, 1, 3] [1, 1, 3]
var input1x1 = [
[1]
]
var input3x3 = [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]
]
var expectedCounterClockwise3x3 = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]
]
var expectedClockwise3x3 = [
[ 3, 2, 1 ],
[ 3, 2, 1 ],
[ 3, 2, 1 ]
]
var input4x4 = [
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]
]
var expectedClockwise4x4 = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]
]
var expectedCounterClockwise4x4 = [
[ 4, 4, 4, 4 ],
[ 3, 3, 3, 3 ],
[ 2, 2, 2, 2 ],
[ 1, 1, 1, 1 ]
]
assert(rotateMtxClockwise(input4x4), expectedClockwise4x4, '90 degree clockwise rotation of 4x4 matrix');
assert(rotateMtxCounterClockwise(input4x4), expectedCounterClockwise4x4, '90 degree counter-clockwise rotation of 4x4 matrix');
assert(rotateMtxClockwise(input3x3), expectedClockwise3x3, '90 degree clockwise rotation of 3x3 matrix');
assert(rotateMtxCounterClockwise(input3x3), expectedCounterClockwise3x3, '90 degree counter-clockwise rotation of 3x3 matrix');
assert(rotateMtxClockwise(input1x1), input1x1, '90 degree clockwise rotation of 1x1 matrix');
assert(rotateMtxCounterClockwise(input1x1), input1x1, '90 degree counter-clockwise rotation of 1x1 matrix');
function rotateMtxClockwise(grid) {
grid = grid.reverse();
return grid.map((n, i) => {
return n.map((m, j) => {
return grid[j][i]
})
})
}
function rotateMtxCounterClockwise(grid) {
grid = grid.reverse();
return grid.map((row, i) => {
return row.map((column, j) => {
return grid[grid.length - 1 - j][grid.length - 1 - i]
})
})
}
function assert(a, b, caption) {
let result = JSON.stringify(a) === JSON.stringify(b) ? ' SUCCEEDS.' : ' FAILS.';
console.log(caption + result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment