Created
May 14, 2021 23:45
-
-
Save alexrhogue/3627fee4fa5a905916349df07cd8b7c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const NUM_CARD_PROP_OPTIONS = 3; | |
const NUM_CARD_PROPS = 4 | |
const BOARD_SIZE = 12; | |
const SET_SIZE = 3; | |
export const getCardProp = () => Math.floor(Math.random() * NUM_CARD_PROP_OPTIONS) | |
export const getCard = () => new Array(NUM_CARD_PROPS).fill().map(getCardProp) | |
export const getBoard = () => new Array(BOARD_SIZE).fill().map(getCard) | |
export const combinations = (arr = [], len) => { | |
if(len === 1) { | |
return arr.map(a => [a]); | |
} | |
if(arr.length === 0) { | |
console.error('arr is empty') | |
} | |
let result = [] | |
for(let i = 0; i < arr.length; i++) { | |
result = [...result, ...combinations([...arr.filter((v, idx) => i != idx)], len - 1).map(a => [arr[i], ...a])]; | |
} | |
return result; | |
} | |
export const isSet = (cards) => { | |
for(let i = 0; i < NUM_CARD_PROPS; i++) { | |
const arr = new Array(NUM_CARD_PROP_OPTIONS).fill(0) | |
for(let j = 0; j < cards.length; j++) { | |
arr[cards[j][i]] += 1; | |
} | |
if(!arr.every(e => e === 1) && !arr.find(e => e === cards.length)) { | |
return false; | |
} | |
} | |
return cards.length > 0; | |
} | |
export const findSet = (board = []) => | |
combinations(board.map((_, i ) => i), SET_SIZE) | |
.find(testIndexes => isSet(testIndexes.map(j => board[j]))) || [] | |
export const playGame = () => { | |
do { | |
const board = getBoard(); | |
console.log('board:', board) | |
const foundSet = findSet(board) | |
if(foundSet) { | |
console.log('found set at', foundSet) | |
console.log(foundSet.map(i => board[i])) | |
break; | |
} | |
console.log('no set \n') | |
} while (true) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment