Skip to content

Instantly share code, notes, and snippets.

@giacomorebonato
Last active February 29, 2024 18:27
Show Gist options
  • Save giacomorebonato/0059fa04f3a96307ebe9045afecf418f to your computer and use it in GitHub Desktop.
Save giacomorebonato/0059fa04f3a96307ebe9045afecf418f to your computer and use it in GitHub Desktop.
Rotate matrix clockwise 90
function rotateMatrix (matrix = []) {
return matrix[0].map(
(_row, i) => getRotatedRow(i, matrix)
)
}
function getRotatedRow (i, matrix) {
return matrix.map(
(_row, y) => matrix[(matrix.length - 1) - y][i]
)
}
module.exports = rotateMatrix
let rotateMatrix = require('../rotateMatrix')
describe('rotateMatrix', () => {
it('rotate a 2x matrix', () => {
let matrix = [
[1, 2],
[3, 4]
]
let rotated = rotateMatrix(matrix)
expect(rotated).toEqual([
[3, 1],
[4, 2]
])
})
it('rotate a 3x matrix', () => {
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
let rotated = rotateMatrix(matrix)
expect(rotated).toEqual([
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
])
})
it('rotates a rectangular matrix', () => {
let matrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]
]
let rotated = rotateMatrix(matrix)
expect(rotated).toEqual([
[6, 1],
[7, 2],
[8, 3],
[9, 4],
[10, 5]
])
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment