Created
November 11, 2018 22:31
-
-
Save AlexeiDarmin/bdcd815e475c03c346aad9f289385734 to your computer and use it in GitHub Desktop.
Rotate a NxN matrix by 90 degrees in place where each pixel in the matrix is 4 bytes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Rotate a NxN matrix by 90 degrees in place where each pixel in the matrix is 4 bytes. | |
*/ | |
/* example call: | |
rotateMatrix(sanitizeData([ | |
[1,2,3], | |
[8,9,4], | |
[7,6,5] | |
])) | |
*/ | |
function rotateMatrix(m: number[][]): number[][] { | |
const size = m.length - 1 | |
const roundedHalf = Math.ceil((size + 1) / 2) | |
for (let r = 0; r < roundedHalf; ++r) { | |
for (let c = r; c < roundedHalf; ++c) { | |
if (r === c) { | |
// Avoid doing XOR on the center cell of an odd sized matrix because that will equal 0. | |
if ((m.length % 2 !== 0 )&& (r === roundedHalf - 1)) { | |
continue | |
} | |
verticalSwap(m, r, c) | |
verticalSwap(m, size - r, size - c) | |
diagonalSwap(m, size - r, c) | |
} else { | |
diagonalSwap(m, r, c) | |
diagonalSwap(m, size - r, size - c) | |
horizontalSwap(m, c, r) | |
} | |
} | |
} | |
return m | |
} | |
function sanitizeData(m: number[][]): number[][] { | |
for (let r = 0; r < m.length; ++r) { | |
for (let c = 0; c < m.length; ++c) { | |
m[r][c] = parseInt(m[r][c].toString(2)) | |
} | |
} | |
return m | |
} | |
function horizontalSwap(m: number[][], r: number, c: number) { | |
const pos1 = { | |
row: r, | |
col: c | |
} | |
const pos2 = { | |
row: r, | |
col: m.length - 1 - c | |
} | |
bitwiseSwap(m, pos1, pos2) | |
} | |
function verticalSwap(m: number[][], r: number, c: number) { | |
const pos1 = { | |
row: r, | |
col: c | |
} | |
const pos2 = { | |
row: m.length - 1 - r, | |
col: c | |
} | |
bitwiseSwap(m, pos1, pos2) | |
} | |
function diagonalSwap(m: number[][], r: number, c: number): void { | |
const pos1 = { | |
row: r, | |
col: c | |
} | |
const pos2 = { | |
row: c, | |
col: r | |
} | |
bitwiseSwap(m, pos1, pos2) | |
} | |
interface IPosition { | |
row: number | |
col: number | |
} | |
function bitwiseSwap(m: number[][], pos1: IPosition, pos2: IPosition): void { | |
m[pos1.row][pos1.col] ^= m[pos2.row][pos2.col] | |
m[pos2.row][pos2.col] ^= m[pos1.row][pos1.col] | |
m[pos1.row][pos1.col] ^= m[pos2.row][pos2.col] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment