Skip to content

Instantly share code, notes, and snippets.

@f
Created May 25, 2022 12:20
Show Gist options
  • Save f/2c2629b46d5a11ed262f978d5d5ca8db to your computer and use it in GitHub Desktop.
Save f/2c2629b46d5a11ed262f978d5d5ca8db to your computer and use it in GitHub Desktop.
const constraints = [
{
nums: [6, 9, 0],
hint: [1, true], // true means correct place
},
{
nums: [7, 4, 1],
hint: [1, false], // false means wrong place
},
{
nums: [5, 0, 4],
hint: [2, false],
},
{
nums: [3, 8, 7],
hint: [0],
},
{
nums: [2, 1, 9],
hint: [1, false],
},
]
function getNumberConstraint(num, hintNums) {
const nums = num
.toString()
.split('')
.map((n) => parseInt(n, 10))
const guess = hintNums.map((hn, i) => {
const includes = nums.includes(hn)
const correctPlace = includes && hintNums[i] === nums[i]
if (includes && correctPlace) return true
if (includes && !correctPlace) return false
return
})
const correctCount = guess.filter((x) => x === true).length
if (correctCount) {
return [correctCount, true]
}
const misplaceCount = guess.filter((x) => x === false).length
if (misplaceCount) {
return [misplaceCount, false]
}
return [0]
}
function checkConstraint(c1, c2) {
return c1[0] === c2[0] && c1[1] === c2[1]
}
const allPossibleNums = Array(999)
.fill()
.map((_, i) => i)
const numberMatchingContstraints = allPossibleNums.filter((i) =>
constraints.every((hint) =>
checkConstraint(getNumberConstraint(i, hint.nums), hint.hint)
)
)
console.log(numberMatchingContstraints)
// [150, 420, 495]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment