Created
November 28, 2017 03:34
-
-
Save AlexJuarez/58fd6b3ffffea219d36f9e290d7097f5 to your computer and use it in GitHub Desktop.
Write a way to play mastermind.
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
// The other player starts with a code that you are trying to guess | |
// the code is 4 digits 1-6, on each guess the other player will | |
// tell you the number of digits in your guess that are in the final solution | |
// and the exact number of digits that matches. | |
// e.g. code: '1234', guess: '1111' => '1 1' | |
const parse = (code) => code.split('').map((n) => parseInt(n, 10)); | |
const MASTER_CODE = parse('1234'); | |
const guess = (code) => code.filter((d, i) => d === MASTER_CODE[i]).length; | |
const setDigit = (code, position, digit) => { | |
const digits = [...code]; | |
digits[position] = digit; | |
return digits; | |
}; | |
const solve = () => { | |
let code = parse('1111'); | |
let prevMatches = guess(code); | |
for (let position = 0; position < code.length; position++) { | |
for (let digit = 2; digit <= 6; digit++) { | |
const next = setDigit(code, position, digit); | |
const matches = guess(next); | |
if (matches < prevMatches) { | |
continue; | |
} | |
if (matches > prevMatches) { | |
code = next; | |
prevMatches = matches; | |
} | |
} | |
} | |
return code.join(''); | |
}; | |
console.log(solve()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment