You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.5 KiB
HTML

<script>
// Based on: https://stackoverflow.com/questions/75486408/n-queens-problem-using-backtracking-in-javascript
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 generate() {
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="generate()">¡Generar!</button>
<script>
generate();
</script>