Available Captures for Rook

EasyArrayMatrixSimulation

Solution

export function numRookCaptures(board: string[][]): number {
  const directions = [
    [0, -1],
    [0, 1],
    [-1, 0],
    [1, 0],
  ] as const;
 
  const findPawn = (y: number, x: number, [dy, dx]: (typeof directions)[number]) => {
    let [ny, nx] = [y + dy, x + dx];
    while (0 <= ny && ny < 8 && 0 <= nx && nx < 8) {
      if (board[ny][nx] === 'p') {
        return true;
      }
      if (board[ny][nx] === 'B') {
        return false;
      }
      [ny, nx] = [ny + dy, nx + dx];
    }
    return false;
  };
 
  for (let y = 0; y < 8; y++) {
    for (let x = 0; x < 8; x++) {
      if (board[y][x] === 'R') {
        return directions.filter((direction) => findPawn(y, x, direction)).length;
      }
    }
  }
  throw new Error('There is no white rock in board.');
}