Random solutions to 10-queens problem
parent
933a8adb2b
commit
2fcb682f26
@ -0,0 +1,96 @@
|
||||
<script>
|
||||
function nQueen(boolArrBoard,row){
|
||||
if(row === boolArrBoard.length){
|
||||
display(boolArrBoard)
|
||||
return 1 //count*
|
||||
}
|
||||
|
||||
let count = 0
|
||||
//placing the queen and checking every row and column*
|
||||
for(let col_ = 0; col_ < boolArrBoard.length; col_++){
|
||||
let col = indexes[col_];
|
||||
//place the queen if it is safe *
|
||||
if(isSafe(boolArrBoard,row,col)){
|
||||
boolArrBoard[row][col] = true
|
||||
count += nQueen(boolArrBoard,row+1)
|
||||
if(count) return 1;
|
||||
boolArrBoard[row][col] = false
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
function isSafe(boolArrBoard,row,col){
|
||||
//vertical*
|
||||
for(let i = 0; i < row; i++){
|
||||
if(boolArrBoard[i][col]){
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
//left diagonal*
|
||||
let maxLeft = Math.min(row,col)
|
||||
for(let i = 1; i <= maxLeft; i++){
|
||||
if(boolArrBoard[row - i][col - i]){
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
//right diagonal*
|
||||
let maxRight = Math.min(row, boolArrBoard.length - col - 1)
|
||||
for(let i = 1; i <= maxRight; i++){
|
||||
if(boolArrBoard[row - i][col + i]){
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
function display(boolArrBoard){
|
||||
let div = document.getElementById("solution");
|
||||
div.innerHTML = "";
|
||||
for( let row in boolArrBoard){
|
||||
for(let column in boolArrBoard[row]){
|
||||
if(boolArrBoard[row][column]){
|
||||
div.append('O ')
|
||||
}
|
||||
else{
|
||||
div.append('+ ')
|
||||
}
|
||||
}
|
||||
div.append('\n')
|
||||
}
|
||||
}
|
||||
|
||||
function shuffle(array) {
|
||||
let currentIndex = array.length;
|
||||
|
||||
// While there remain elements to shuffle...
|
||||
while (currentIndex != 0) {
|
||||
|
||||
// Pick a remaining element...
|
||||
let randomIndex = Math.floor(Math.random() * currentIndex);
|
||||
currentIndex--;
|
||||
|
||||
// And swap it with the current element.
|
||||
[array[currentIndex], array[randomIndex]] = [
|
||||
array[randomIndex], array[currentIndex]];
|
||||
}
|
||||
}
|
||||
|
||||
var indexes;
|
||||
function generar() {
|
||||
let n = 10
|
||||
let boolArrBoard = Array.from({length: n}, () => {
|
||||
return new Array(n).fill(false)
|
||||
})
|
||||
indexes = Array(n).fill().map((x,i)=>i)
|
||||
shuffle(indexes);
|
||||
nQueen(boolArrBoard,0)
|
||||
}
|
||||
</script>
|
||||
<pre id="solution"></pre>
|
||||
<button onclick="generar()">¡Generar!</button>
|
||||
<script>
|
||||
generar();
|
||||
</script>
|
Loading…
Reference in New Issue