Last active
June 16, 2024 07:06
-
-
Save zsteva/9a146d63c3e0c19927c3cc2418c9d68f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
var cells = [ ... document.getElementById("queens-grid").querySelectorAll(".queens-cell") ]; | |
var size = Math.sqrt(cells.length); | |
var map = cells.map(e => e.className.match(/cell-color-(\d+)/)[1]); | |
var queens = Array(map.length).fill(0); | |
var colors = map.reduce((a, c) => (a[c]=0, a), {}); | |
var cols = Array(size).fill(0); | |
var take = (i,j) => { queens[i+j] = 1; cols[j] = 1; colors[map[i+j]] = 1; }; | |
var retr = (i,j) => { queens[i+j] = 0; cols[j] = 0; colors[map[i+j]] = 0; }; | |
var check = (i,j) => { | |
return cols[j] == 0 | |
&& (i >= size && j > 0 ? queens[i+j-size-1] == 0 : true) | |
&& (i >= size && j < size ? queens[i+j-size+1] == 0 : true) | |
&& colors[map[i+j]] == 0; | |
}; | |
var solve = (i = 0) => { | |
if (i >= map.length) { | |
return 1; | |
} | |
for (var j = 0; j < size; j++) { | |
if (check(i, j)) { | |
take(i, j); | |
if (solve(i + size)) { | |
return 1; | |
} | |
retr(i, j); | |
} | |
} | |
return 0; | |
}; | |
var placequeen = (n) => { | |
['mousedown', 'mouseup', 'mousedown', 'mouseup'].forEach(ev => { | |
cells[n].dispatchEvent(new MouseEvent(ev, { bubbles: true, cancelable: true, })); | |
}); | |
}; | |
if (solve()) | |
queens.forEach((e, i) => e ? placequeen(i) : null); | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment