Skip to content

Instantly share code, notes, and snippets.

@rla
Created April 5, 2017 16:40
Show Gist options
  • Save rla/51d30dc5f774c803731ca77b1f7f9736 to your computer and use it in GitHub Desktop.
Save rla/51d30dc5f774c803731ca77b1f7f9736 to your computer and use it in GitHub Desktop.
Queens ported to yield and generators
// http://www.javaist.com/blog/2008/11/06/eight-queens-problem-in-prolog/
const EMPTY_LIST = [];
function* between(start, end) {
for (let v = start; v < end; v++) {
yield v;
}
}
function* solution(X, N) {
if (X > 0) {
for (const Others of solution(X - 1, N)) {
for (const Y of between(1, N + 1)) {
if (noAttack(X, Y, Others)) {
yield [[X, Y], Others];
}
}
}
} else {
yield EMPTY_LIST;
}
};
const noAttack = (X, Y, Solution) => {
if (Solution === EMPTY_LIST) {
return true;
} else {
const [[X1, Y1], Others] = Solution;
return Y !== Y1 &&
Y1 - Y !== X1 - X &&
Y1 - Y !== X - X1 && noAttack(X, Y, Others);
}
};
const n = 20;
const sol = solution(n, n);
const write = ([[X, Y], Others]) => {
console.log(X + '/' + Y);
if (Others !== EMPTY_LIST) {
write(Others);
}
};
write(sol.next().value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment