Created
September 15, 2017 03:18
-
-
Save pengcheng95/cd36e5ca96650e3f3c52c62fc12beeef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>n-queens solver</title> | |
</head> | |
<body> | |
<script type="src/queenWorker.js"></script> | |
<script> | |
var num = parseInt(prompt("enter num")); | |
var all = (1 << num) - 1; | |
count = 0; | |
for (var i = 0; i < num; i++) { | |
var cols = 2 ** i; | |
var ld = 2 ** (i + 1); | |
var rd = 0; | |
if (i > 0) { | |
rd = 2 ** (i - 1); | |
} | |
var myWorker = new Worker('queenWorker.js'); | |
myWorker.addEventListener('message', function(e) { | |
count += e.data; | |
console.log('worker count: ', e.data); | |
}, false); | |
myWorker.postMessage([ld, cols, rd, all]); | |
} | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
self.addEventListener('message', function(e) { | |
let count = 0; | |
var findSolutions = function(ld, cols, rd, all) { | |
let poss = ~(ld | cols | rd) & all; | |
if (cols === all) { | |
count++; | |
} | |
while (poss) { | |
let negPoss = poss * -1; | |
let bit = poss & negPoss; | |
//let bit = poss & -poss; | |
poss = poss - bit; | |
findSolutions((ld | bit) << 1, cols | bit, (rd | bit) >> 1, all); | |
} | |
}; | |
findSolutions(e.data[0], e.data[1], e.data[2], e.data[3]); | |
self.postMessage(count); | |
}, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment