-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolvers.js
98 lines (83 loc) · 2.7 KB
/
solvers.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Write code here that will find the solution count for a board of any size.
// hint: you'll need to do a full-search of all possible arrangements of pieces!
// (There are also optimizations that will allow you to skip a lot of the dead search space)
var makeEmptyMatrix = function(n){
return _(_.range(n)).map(function(){
return _(_.range(n)).map(function(){
return 0;
});
});
};
window.toggle = function (array) {
if (array[0] === 1) {
array[0] = 0;
return array[0];
}
if (array[0] === 0) {
array[0] = 1;
return array[0];
}
};
window.findNRooksSolution = function(n){
var solution = undefined;
console.log('Single solution for ' + n + ' rooks:', solution);
return solution;
};
window.countNRooksSolutions = function(n){
var factorial = function (n){
if (n===0){
return 1;
} else {
return (n * factorial(n - 1));
}
};
var solutionCount = factorial(n);
console.log('Number of solutions for ' + n + ' rooks:', solutionCount);
return solutionCount;
};
// N-queens solution
var nQueens = function(n, solutionCount, row, columnCollisions, majorDiaCollisions, minorDiaCollisions){
columnCollisions = columnCollisions || {};
majorDiaCollisions = majorDiaCollisions || {};
minorDiaCollisions = minorDiaCollisions || {};
row = row || 0;
solutionCount = solutionCount || 0;
for(var i = 0; i < n; i++) {
if (row < n) {
// if there are no conflicts...
if (columnCollisions[i] !== true || columnCollisions[i] === undefined) {
if (majorDiaCollisions[i - row] !== true || majorDiaCollisions[i - row] === undefined) {
if (minorDiaCollisions[i + row] !== true || minorDiaCollisions[i + row] === undefined) {
columnCollisions[i] = true;
majorDiaCollisions[i - row] = true;
minorDiaCollisions[i + row] = true;
// do a deep copy of each object
var cloneColumnCollisions = deepCopy(columnCollisions);
var cloneMajorDiaCollisions = deepCopy(majorDiaCollisions);
var cloneMinorDiaCollisions = deepCopy(minorDiaCollisions);
nQueens(n, solutionCount, row + 1, cloneColumnCollisions, cloneMajorDiaCollisions, cloneMinorDiaCollisions);
}
}
}
} else {
solutionCount += 1;
}
}
return solutionCount;
};
var deepCopy = function(obj) {
var clone = {};
for (var key in obj) {
clone[key] = obj[key];
}
return clone;
};
console.log(nQueens(4));
// This function uses a board visualizer lets you view an interactive version of any piece matrix.
window.displayBoard = function(matrix){
$('body').html(
new BoardView({
model: new Board(matrix)
}).render()
);
};