Skip to content

Instantly share code, notes, and snippets.

@umutbasal
Created May 25, 2022 17:28
Show Gist options
  • Save umutbasal/9986183a103dc86df29321a07ef67e98 to your computer and use it in GitHub Desktop.
Save umutbasal/9986183a103dc86df29321a07ef67e98 to your computer and use it in GitHub Desktop.
const problem = {
operators: {
has: (possibility, numbers, has) => possibility.reduce((acc, cur) => numbers.includes(cur) ? acc + 1 : acc, 0) === has,
rightPlace: (possibility, numbers) => possibility.some(x => possibility.indexOf(x) === numbers.indexOf(x)),
},
possibilities: Array.from(Array(1000).keys()).map(x => x.toString().padStart(3, '0').split('').map(x => parseInt(x))),
sets: [
{ numbers: [6, 9, 0], has: 1, rightPlace: true }, // One number is correct and right place
{ numbers: [7, 4, 1], has: 1, rightPlace: false }, // One number is correct but wrong place
{ numbers: [5, 0, 4], has: 2, rightPlace: false }, // Two numbers are correct but wrong place
{ numbers: [3, 8, 7], has: 0, rightPlace: false }, // Nothing is correct
{ numbers: [2, 1, 9], has: 1, rightPlace: false }, // One number is correct but wrong place
]
};
let possibilities = problem.possibilities;
problem.sets.forEach(set => {
possibilities = possibilities
.filter(possibility => problem.operators.has(possibility, set.numbers, set.has))
.filter(possibility => problem.operators.rightPlace(possibility, set.numbers) === set.rightPlace);
})
console.log(possibilities);
@umutbasal
Copy link
Author

umutbasal commented May 25, 2022

and some joke

const problem = `Has one number of 690 in the right place
Has one number of 741 in the wrong place
Has two numbers of 504 in the wrong place
Has no numbers of 387 in the wrong place
Has one number of 219 in the wrong place`;

const numberMap = {
	"no": 0,
	"one": 1,
	"two": 2,
}

const regex = new RegExp(`^Has (.*) number[s]? of (\\d+) in the (.*) place$`, 'gm');

let possibilities = Array.from(Array(1000).keys()).map(x => x.toString().padStart(3, '0').split('').map(x => parseInt(x)));

while (null != (match = regex.exec(problem))) {
	[, has, set, place] = match;
	set = set.split('').map(x => parseInt(x));

	possibilities = possibilities
		.filter(possibility => possibility.reduce((acc, cur) => set.includes(cur) ? acc + 1 : acc, 0) === numberMap[has])
		.filter(possibility => possibility.some(x => possibility.indexOf(x) === set.indexOf(x)) === (place === 'right'));
}

console.log(possibilities);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment