Skip to content

Instantly share code, notes, and snippets.

@mkstix6
Created March 10, 2021 20:47
Show Gist options
  • Save mkstix6/91011013fd95c6a8727e0f2a14e812d5 to your computer and use it in GitHub Desktop.
Save mkstix6/91011013fd95c6a8727e0f2a14e812d5 to your computer and use it in GitHub Desktop.
Rendezvous with Cassidoo #186 - Interview question of the week - validTTTPosition
const validTTTPosition = (boardInput) => {
// Assuming boardInput of form ["XOX", " X ", " "]
// Re-organise board chars; I'm comfy with arrays.
const boardChars = [...boardInput.join("")];
// Player char counts
const Xcount = boardChars.filter((char) => char === "X").length;
const Ocount = boardChars.filter((char) => char === "O").length;
// Mustn't have less Xs than Os; assume X goes first
if (Xcount < Ocount) return false;
// Mustn't have 2 more Xs than Os; assume we take turns
if (Xcount - Ocount > 1) return false;
// Ok, let's just compute the 8 board "words" up front #noPerf 🤷
const boardWords = [
`${boardChars[0]}${boardChars[1]}${boardChars[2]}`, // Horizontal
`${boardChars[3]}${boardChars[4]}${boardChars[5]}`, // Horizontal
`${boardChars[6]}${boardChars[7]}${boardChars[8]}`, // Horizontal
`${boardChars[0]}${boardChars[3]}${boardChars[6]}`, // Vertical
`${boardChars[1]}${boardChars[4]}${boardChars[7]}`, // Vertical
`${boardChars[2]}${boardChars[5]}${boardChars[8]}`, // Vertical
`${boardChars[0]}${boardChars[4]}${boardChars[8]}`, // Diagonal
`${boardChars[2]}${boardChars[4]}${boardChars[6]}`, // Diagonal
];
// If Xs win there must be one more Xs, than Os, on the board.
if (boardWords.includes("XXX") && Xcount !== Ocount + 1) {
return false;
}
// If Os win there must be equal counts of Xs and Os on the board.
if (boardWords.includes("OOO") && Xcount !== Ocount) {
return false;
}
// Exhausted checks, assume board position is valid 😅
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment