-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnodeQueensChild.js
More file actions
54 lines (46 loc) · 1.69 KB
/
nodeQueensChild.js
File metadata and controls
54 lines (46 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
github.com/relloller/node-queens
Victor Shaw
vshaw168@gmail.com
3/24/17
nodeQueensChild.js
*This is script for the child process, please execute the parent process nodeQueensParent.js
*/
'use strict';
var nQ_num = parseInt(process.argv[2]);
var nQ_posy = parseInt(process.argv[3]);
var nQ_pos = [0, nQ_posy];
process.stdin.on('data', function(data) {
nQ_posy = JSON.parse(data);
nQ_pos = [0,nQ_posy];
nodeQueensChild();
});
process.stderr.on('data', function(data) {
console.log('ps stderr', data);
});
nodeQueensChild();
function nodeQueensChild() {
var nqRes = nQueens(nQ_num, [nQ_pos]);
if (nQ_num % 2 === 0 || Math.floor(nQ_num / 2) !== nQ_posy) nqRes *= 2; // for rows with symmetry, we multiple solutions by 2
process.stdout.write(JSON.stringify(nqRes));
}
function nQueens(boardsize, arr = []) {
var solutions=0;
function nQueensRec(boardsize, arr) {
var arrL = arr.length;
if (arrL === boardsize) solutions++;
else for(var q = 0; q < boardsize; q++) {
if(checkSpaceEach(arr, [arrL, q])) nQueensRec(boardsize, arr.concat([[arrL, q]]));
}
}
nQueensRec(boardsize, arr);
return solutions;
}
function checkRow(a, b) { return (a[0] !== b[0])} //checkRow is not needed in this recursive implementation and has been removed from functions
function checkColumn(a, b) { return (a[1] !== b[1])}
function checkDiagonal(a, b) { return (Math.abs(a[0] - b[0]) !== Math.abs(a[1] - b[1]))}
function checkSpace(a, b) {return (checkColumn(a, b) && checkDiagonal(a, b))}
function checkSpaceEach(arr, pos) {
for (var i = 0; i < arr.length; i++) if(!checkSpace(arr[i],pos)) return false;
return true;
}