Skip to content

Instantly share code, notes, and snippets.

@bioball
Last active December 29, 2015 03:29
Show Gist options
  • Save bioball/7607592 to your computer and use it in GitHub Desktop.
Save bioball/7607592 to your computer and use it in GitHub Desktop.
This might just be the fastest possible non-bitwise JavaScript algorithm for the N Queens puzzle http://en.wikipedia.org/wiki/Eight_queens_puzzle. This was written in collaboration with githib.com/stites
var nQueens = function(n){
if(n === 1){ return 1; }
n = n - 1;
var
m = Math.ceil(n/2),
count = 0,
col = new Int8Array(n + 1),
maj = new Int8Array(n + n + 1),
min = new Int8Array(n + n + 1);
var recurse = function(x, col, maj, min){
for(var y = 0; y <= n; y++){
if(maj[n + x - y] || min[x + y]){
continue;
}
if(!col[y]){
if(x === n){
return count++;
}
col[y] = 1;
maj[n + x - y] = 1;
min[x + y] = 1;
recurse(x + 1, col, maj, min);
col[y] = 0;
maj[n + x - y] = 0;
min[x + y] = 0;
}
}
}
for(var i = 0; i < m; i++){
col[i] = 1;
maj[n - i] = 1;
min[i] = 1;
recurse(1, col, maj, min);
col[i] = 0;
maj[n - i] = 0;
min[i] = 0;
}
count *= 2;
if(!(n % 2)){
col[m] = 1;
maj[n - m] = 1;
min[m] = 1;
recurse(1, col, maj, min);
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment