Problems › TypeScript › patterns
Read the floor plan in a spiral
A stocktake walks a warehouse grid from the outside in, clockwise, so the counter never crosses their own path.
- Start at the top left and move right along the top row.
- Then down the right edge, back along the bottom, up the left, and inwards.
- Every cell appears exactly once.
- An empty grid gives an empty walk.
spiralWalk(bays: list<list<int>>) → list<int>
Where you start
function spiralWalk(bays: number[][]): number[] {
}
Worked examples
| Call | Result |
|---|---|
spiralWalk([[1,2,3],[4,5,6],[7,8,9]]) | [1,2,3,6,9,8,7,4,5] |
spiralWalk([[1,2],[3,4]]) | [1,2,4,3] |
spiralWalk([[1,2,3]]) | [1,2,3] |
spiralWalk([[1],[2],[3]]) | [1,2,3] |
Hint
Track four edges — top, bottom, left, right. Walk one of them, then pull that edge in, and stop when they cross.
Reference solution in TypeScript
function spiralWalk(bays: number[][]): number[] {
const walk: number[] = [];
if (bays.length === 0) return walk;
let top = 0;
let bottom = bays.length - 1;
let left = 0;
let right = bays[0].length - 1;
while (top <= bottom && left <= right) {
for (let c = left; c <= right; c += 1) walk.push(bays[top][c]);
top += 1;
for (let r = top; r <= bottom; r += 1) walk.push(bays[r][right]);
right -= 1;
if (top <= bottom) {
for (let c = right; c >= left; c -= 1) walk.push(bays[bottom][c]);
bottom -= 1;
}
if (left <= right) {
for (let r = bottom; r >= top; r -= 1) walk.push(bays[r][left]);
left += 1;
}
}
return walk;
}