'How to randomly select divs from inside another div?
I am struggling to randomly select some divs (9 in this case) to place bombs/mines for those selected tiles.
My code for this is:
function place_mines() {
if (document.getElementById("difficulty").selectedIndex == "2") {
for (var u = 0; u < 8; u++) {
}
}
}
Solution 1:[1]
I would use a different approach. I would make a list of tile objects and generate the html from the list. This lets you flag an object as bomb without revealing it to the user by adding it as class name.
After you generated the list, you can take a random subset and flag it as bombs. You could use this approach for example: Sampling a random subset from an array.
Solution 2:[2]
I suggest you to give id to the tiles, to later you generate random id , and map the generated id to the tiles
Solution 3:[3]
What worked for me was I added a counter to index the elements. After that, made an array of 9 random numbers from 0-80 (counter starts at 0), checked if the id of the tile selected is in that array, if it was then that tile has a mine else its a normal tile.
tile.setAttribute("id",counter);counter++;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tobias |
| Solution 2 | Tinsae |
| Solution 3 | Vatsal Rajyaguru |

