I have the below code that generates non repeating random numbers for a bingo card. For you to understand, I am also putting HTML code of the same:
window.onload = newCard;
var usedNums = new Array(76);
function newCard() {
if (document.getElementById) {
for (var i=0; i<24; i++) {
setSquare(i);
}
}
else {
alert("Sorry, your browser doesn't support this script");
}
}
function setSquare(thisSquare) {
var currSquare = "square" + thisSquare;
var colPlace = new Array(0,1,2,3,4,0,1,2,3,4,0,1,3,4,0,1,2,3,4,0,1,2,3,4);
var colBasis = colPlace[thisSquare] * 15;
var newNum;
do {
newNum = colBasis + getNewNum() + 1;
}
while (usedNums[newNum]);
usedNums[newNum] = true;
document.getElementById(currSquare).innerHTML = newNum;
}
function getNewNum() {
return Math.floor(Math.random() * 15);
}
==================================================================================
<html>
<head>
<title>Make Your Own Bingo Card</title>
<link rel="stylesheet" rev="stylesheet" href="script.css" />
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h1>Create A Bingo Card</h1>
<table>
<tr>
<th width="20%">B</th>
<th width="20%">I</th>
<th width="20%">N</th>
<th width="20%">G</th>
<th width="20%">O</th>
</tr>
<tr>
<td id="square0"> </td>
<td id="square1"> </td>
<td id="square2"> </td>
<td id="square3"> </td>
<td id="square4"> </td>
</tr>
<tr>
<td id="square5"> </td>
<td id="square6"> </td>
<td id="square7"> </td>
<td id="square8"> </td>
<td id="square9"> </td>
</tr>
<tr>
<td id="square10"> </td>
<td id="square11"> </td>
<td id="free">Free</td>
<td id="square12"> </td>
<td id="square13"> </td>
</tr>
<tr>
<td id="square14"> </td>
<td id="square15"> </td>
<td id="square16"> </td>
<td id="square17"> </td>
<td id="square18"> </td>
</tr>
<tr>
<td id="square19"> </td>
<td id="square20"> </td>
<td id="square21"> </td>
<td id="square22"> </td>
<td id="square23"> </td>
</tr>
</table>
<p><a href="script.html" id="reload">Click here</a> to create a new card</p>
</body>
</html>
Is it correct that, "while (usedNums[newNum]);" is checking whether a number exists in the array? Is that correct that, "usedNums[newNum] = true;" is setting the item in the array to a non-zero value?
If the above two questions are correct, then I am wondering, how is it generating non-repeating random numbers?
If I make "usedNums[newNum]" to false, it generates repeating numbers, can you please explain the backend functionality of this statement?
If convenient, also paste the reference links, I want to study in detail about this.