Skip to content

Instantly share code, notes, and snippets.

@FelixLuciano
Last active March 9, 2021 20:24
Show Gist options
  • Save FelixLuciano/f11ca5a2ba44f3679105a78eaab516cb to your computer and use it in GitHub Desktop.
Save FelixLuciano/f11ca5a2ba44f3679105a78eaab516cb to your computer and use it in GitHub Desktop.
rendezvous with cassidoo #186 - Interview question of the week
/**
* From: https://buttondown.email/cassidoo/archive/37ac19b1-2bea-4354-8860-3fdb47e456cd
* @param {string[]} board A Tic Tac Toe board
* @returns {boolean} If and only if it’s possible to reach this board position during the course of a valid tic-tac-toe game.
* @example
* const board = ["XOX", "O O", "XOX"]
*
* $ validTTTPosition(board)
* -> true
*/
function validTTTPosition (board) {
let count = {}
for (let y = 0; y < board.length; y++)
for (let x = 0; x < board[y].length; x++) {
const char = board[y][x]
if (char === " ") continue
count[char] = count[char] + 1 || 1
for (let a = 0, b = 1; b>=0; b-=a>=b, a+=a<b)
for (let l = 1; board[y+l*a]?.[x+l*b] === char; l++)
if (count.wins = count.wins + (l === 2) || 1 > 1) return false
}
return !(Math.abs((count.X||0) - (count.O||0) - .5) >= 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment