Skip to content

Instantly share code, notes, and snippets.

@Sheraff
Created August 20, 2020 13:26
Show Gist options
  • Save Sheraff/4758ce70062d3dc5f3f8a4a144b55e59 to your computer and use it in GitHub Desktop.
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)
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