forked from hackademymx/future-developers-practica
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VictorHugoGomezChavez.js
73 lines (58 loc) · 2.12 KB
/
VictorHugoGomezChavez.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
class QueenPosition {
constructor(rowIndex, columnIndex) {
this.rowIndex = rowIndex
this.columnIndex = columnIndex
}
get leftDiagonal() {
return this.rowIndex - this.columnIndex
}
get rigthDiagonal() {
return this.rowIndex + this.columnIndex
}
}
function isSafe(queensPositions, rowIndex, columnIndex) {
const newQueenPosition = new QueenPosition(rowIndex, columnIndex)
for(let queenIndex = 0; queenIndex < queensPositions.length; queenIndex++) {
const currentQueenPosition = queensPositions[queenIndex]
if(
currentQueenPosition &&
(
newQueenPosition.columnIndex === currentQueenPosition.columnIndex ||
newQueenPosition.rowIndex === currentQueenPosition.rowIndex ||
newQueenPosition.leftDiagonal === currentQueenPosition.leftDiagonal ||
newQueenPosition.rigthDiagonal === currentQueenPosition.rigthDiagonal
)
) {
return false
}
}
return true
}
function allQueensSet(queensPositions) {
return queensPositions.every(position => position !==null)
}
function nQueensRecursive(solutions, previousQueensPositions, queensCount, columnIndex) {
const queensPositions = [...previousQueensPositions].map(queenPosition => {
return !queenPosition ? queenPosition : new QueenPosition(queenPosition.rowIndex, queenPosition.columnIndex)
})
if(allQueensSet(queensPositions)) {
solutions.push(queensPositions)
return true
}
for(let rowIndex = 0; rowIndex < queensCount; rowIndex++) {
if(isSafe(queensPositions, rowIndex, columnIndex)) {
queensPositions[rowIndex] = new QueenPosition(rowIndex, columnIndex)
nQueensRecursive(solutions, queensPositions, queensCount, columnIndex + 1)
queensPositions[rowIndex] = null
}
}
return false
}
function nQueens(queensCount) {
const queensPostions = Array(queensCount).fill(null)
const solutions = []
nQueensRecursive(solutions, queensPostions, queensCount, 0)
return solutions
}
const results = nQueens(4)
console.log(results)