Drill

ProblemsJavaScript › patterns

Read the floor plan in a spiral

hardpatternsGridsArraysJavaScript

A stocktake walks a warehouse grid from the outside in, clockwise, so the counter never crosses their own path.

spiralWalk(bays: list<list<int>>) → list<int>

Solve it in the editor →

Where you start

function spiralWalk(bays) {
  
}

Worked examples

CallResult
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 JavaScript
function spiralWalk(bays) {
  const walk = [];
  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;
}

The same problem in another language

More patterns problems in JavaScript