DEV Community

loading...

Discussion on: Daily Challenge #92 - Boggle Board

Collapse
erezwanderman profile image
erezwanderman

Shorter ver:

const isValid = (board: string[][], guess: string, prevCoords?: [number, number]) => {
  if (guess === '') return true;
  if (!prevCoords) {
    const coords = [].concat(...board.map((row, r) => row.map((val, c) => [r, c])));
    return coords.some(c => isValid(board, guess, c));
  } else {
    if (board[prevCoords[0]][prevCoords[1]] !== guess[0]) return false;

    const temp = board[prevCoords[0]][prevCoords[1]];
    board[prevCoords[0]][prevCoords[1]] = '*';
    const answer = [
        [prevCoords[0] - 1, prevCoords[1] - 1],
        [prevCoords[0] - 1, prevCoords[1]    ],
        [prevCoords[0] - 1, prevCoords[1] + 1],
        [prevCoords[0]    , prevCoords[1] - 1],

        [prevCoords[0]    , prevCoords[1] + 1],
        [prevCoords[0] + 1, prevCoords[1] - 1],
        [prevCoords[0] + 1, prevCoords[1]    ],
        [prevCoords[0] + 1, prevCoords[1] + 1]
    ]
    .filter(([r, c]) => r >= 0 && c >= 0 && r < board.length && c < board[0].length)
    .some(([r, c]) => isValid(board, guess.substring(1), [r, c]));
    board[prevCoords[0]][prevCoords[1]] = temp;
    return answer;
  }
}

const testBoard = [
  ["I","L","A","W"],
  ["B","N","G","E"],
  ["I","U","A","O"],
  ["A","S","R","L"]
];

const testWords = ['BINGO', 'LINGO', 'ILNBIA', 'BUNGIE', 'BINS', 'SINUS'];
for (const word of testWords) {
  console.log(word, isValid(testBoard, word));
}