Created
August 20, 2020 13:26
-
-
Save Sheraff/4758ce70062d3dc5f3f8a4a144b55e59 to your computer and use it in GitHub Desktop.
takes a 2D matrix and iterates over it in isometric order (diagonal by diagonal)
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
const nbColumns = 5 | |
const nbRows = 5 | |
const matrix = new Array(nbColumns) | |
.fill(null) | |
.map(() => new Array(nbRows) | |
.fill(null) | |
.map(() => 0) | |
) | |
drawMatrix(matrix) | |
let counter = 0 | |
for(let i = 0; i < Math.max(nbColumns, nbRows) * 2 - 1; i++) { | |
for (let j = Math.min(i, nbColumns - 1); j >= 0; j--) { | |
if (j < nbColumns && i-j < nbRows) | |
matrix[j][i-j] = counter++ | |
} | |
} | |
drawMatrix(matrix) | |
const isometric = drawIsometric(matrix) | |
drawMatrix(isometric) | |
function drawMatrix(matrix) { | |
let output = '\n' | |
for (const line of matrix) { | |
if(!line) { | |
output += '\n' | |
continue | |
} | |
for (const cell of line) { | |
if(cell === null) | |
output += ' ' | |
else { | |
if(cell < 10 && cell >= 0) | |
output += '0' | |
output += cell + ' ' | |
} | |
} | |
output += '\n' | |
} | |
console.log(output) | |
} | |
function drawIsometric(matrix) { | |
const diagonalCount = Math.max(nbColumns, nbRows) * 2 - 1 | |
const result = new Array(diagonalCount) | |
.fill(null) | |
.map(() => new Array(diagonalCount) | |
.fill(null) | |
) | |
for(let i = 0; i < Math.max(nbColumns, nbRows) * 2 - 1; i++) { | |
for (let j = Math.min(i, nbColumns - 1); j >= 0; j--) { | |
if (j < nbColumns && i-j < nbRows) | |
result[i][Math.floor(diagonalCount / 2 - j + i / 2)] = matrix[j][i-j] | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment