Skip to content

Instantly share code, notes, and snippets.

@FelixLuciano
Last active January 25, 2021 17:40
Show Gist options
  • Save FelixLuciano/8488b5ffc42a5ac331dfa96aea1d991f to your computer and use it in GitHub Desktop.
Save FelixLuciano/8488b5ffc42a5ac331dfa96aea1d991f to your computer and use it in GitHub Desktop.
rendezvous with cassidoo #180 - Interview question of the week
/* Given an n x n array, rotate it 90 degrees without making a new array.
* rotate90([[1,2,3], [4,5,6], [7,8,9]])
* -> [[7,4,1], [8,5,2], [9,6,3]]
*/
function rotate90(arr, isClockwise = true) {
const size = arr.length - 1
for (let y = 0, length = size; y <= size && length >= 0; y++, length--) {
for (let x = y; x < length; x++) {
let [x1, y1] = [x, y]
let value = arr[y1][x1]
do {
const x2 = isClockwise ? size - y1 : y1
const y2 = isClockwise ? x1 : size - x1
const temp = arr[y2][x2]
arr[y2][x2] = value
value = temp
x1 = x2
y1 = y2
} while (!(x1 === x && y1 === y))
}
}
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment