Skip to content

Commit 18ba3a4

Browse files
juffalowtrekhleb
authored andcommitted
Add N queens problem bitwise solution (trekhleb#15)
* Add N queens problem bitwise solution * Update code to corespond with eslint
1 parent 5a57c5f commit 18ba3a4

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# N-Queens Problem with Bitwise Solution
2+
3+
Write a function that will find all possible solutions to the N queens problem for a given N.
4+
5+
## References
6+
7+
- [Wikipedia](https://en.wikipedia.org/wiki/Eight_queens_puzzle)
8+
- [GREG TROWBRIDGE](http://gregtrowbridge.com/a-bitwise-solution-to-the-n-queens-problem-in-javascript/)
9+
- [Backtracking Algorithms in MCPL using Bit Patterns and Recursion](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.51.7113&rep=rep1&type=pdf)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import nQueensBitwise from '../nQueensBitwise';
2+
3+
describe('nQueensBitwise', () => {
4+
it('should have solutions for 4 to N queens', () => {
5+
const solutionFor4 = nQueensBitwise(4);
6+
expect(solutionFor4).toBe(2);
7+
8+
const solutionFor5 = nQueensBitwise(5);
9+
expect(solutionFor5).toBe(10);
10+
11+
const solutionFor6 = nQueensBitwise(6);
12+
expect(solutionFor6).toBe(4);
13+
14+
const solutionFor7 = nQueensBitwise(7);
15+
expect(solutionFor7).toBe(40);
16+
17+
const solutionFor8 = nQueensBitwise(8);
18+
expect(solutionFor8).toBe(92);
19+
20+
const solutionFor9 = nQueensBitwise(9);
21+
expect(solutionFor9).toBe(352);
22+
23+
const solutionFor10 = nQueensBitwise(10);
24+
expect(solutionFor10).toBe(724);
25+
});
26+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
export default function (n) {
2+
// Keeps track of the # of valid solutions
3+
let count = 0;
4+
5+
// Helps identify valid solutions
6+
const done = (2 ** n) - 1;
7+
8+
// Checks all possible board configurations
9+
const innerRecurse = (ld, col, rd) => {
10+
// All columns are occupied,
11+
// so the solution must be complete
12+
if (col === done) {
13+
count += 1;
14+
return;
15+
}
16+
17+
// Gets a bit sequence with "1"s
18+
// whereever there is an open "slot"
19+
let poss = ~(ld | rd | col);
20+
21+
// Loops as long as there is a valid
22+
// place to put another queen.
23+
while (poss & done) {
24+
const bit = poss & -poss;
25+
poss -= bit;
26+
innerRecurse((ld | bit) >> 1, col | bit, (rd | bit) << 1);
27+
}
28+
};
29+
30+
innerRecurse(0, 0, 0);
31+
32+
return count;
33+
}

0 commit comments

Comments
 (0)