Print matrix coordinates layer by layer
suggest changefunction* spiralCoordinates(rows, columns) {
let top = 0;
let bottom = rows - 1;
let left = 0;
let right = columns - 1;
while (top <= bottom && left <= right) {
for (let column = left; column <= right; column++) yield [top, column];
top++;
for (let row = top; row <= bottom; row++) yield [row, right];
right--;
if (top <= bottom) {
for (let column = right; column >= left; column--) yield [bottom, column];
bottom--;
}
if (left <= right) {
for (let row = bottom; row >= top; row--) yield [row, left];
left++;
}
}
}
for (const [row, column] of spiralCoordinates(6, 4)) {
console.log(`${row},${column}`);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents