Created
September 1, 2019 10:35
-
-
Save dosbol/923549191842c92f9429875265db6c9b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 selectRandom = numbers => { | |
return numbers[Math.floor(Math.random() * numbers.length)]; | |
} | |
const strategy1 = numbers => { | |
return numbers[0]; | |
} | |
const strategy2 = numbers => { | |
return selectRandom(numbers); | |
} | |
const without = (numbers, value) => { | |
let index = numbers.indexOf(value); | |
return [...numbers.slice(0, index), ...numbers.slice(index + 1)]; | |
} | |
const winMessage = score => { | |
if (score[0] > score[1]) { | |
return `Player1 won`; | |
} else if (score[1] > score[0]) { | |
return `Player2 won`; | |
} else { | |
return `Draw`; | |
} | |
} | |
const endMessage = state => { | |
return `Total: ${state.score} \n ${winMessage(state.score)}`; | |
} | |
const turnMessage = state => { | |
return `Player1 chose ${state.num1}` + | |
`\nPlayer2 chose ${state.num2}`; | |
} | |
const newScore = ([score1, score2], num1, num2) => { | |
if (num1 > num2) { | |
return [score1 + 1, score2]; | |
} else if (num2 > num1) { | |
return [score1, score2 + 1]; | |
} else { | |
return [score1, score2]; | |
} | |
} | |
const nextState = state => { | |
let num1 = strategy1(state.numbers1); | |
let num2 = strategy2(state.numbers2); | |
return { numbers1: without(state.numbers1, num1), | |
numbers2: without(state.numbers2, num2), | |
score: newScore(state.score, num1, num2), | |
num1, | |
num2 | |
} | |
} | |
const last = arr => { | |
return arr[arr.length - 1]; | |
} | |
const report = (states, onTurn, onEnd) => { | |
return states.slice(1).map(onTurn).join("\n") + | |
"\n" + onEnd(last(states)); | |
} | |
const recur = (states, stateChange, endCondition) => { | |
if(endCondition(last(states))) { | |
return states; | |
} else { | |
return recur(states.concat(stateChange(last(states))), stateChange, endCondition); | |
} | |
} | |
const runGame = () => { | |
let states = [{numbers1: [4, 5, 3], | |
numbers2: [4, 5, 3], | |
score: [0, 0]}]; | |
return recur(states, nextState, (state) => {return state.numbers1.length === 0}); | |
} | |
console.log(report(runGame(), turnMessage, endMessage)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment