Jonas  Kroneberg Jonas Kroneberg - 1 year ago 76
Javascript Question

Lottery with Supernumber

I came across the challenge of building a random numbers generator for the lottery.

6 numbers, which are between 1 and 49, none of which appears to be twice, in ascending order. One 7th number, the super-seven, not sorted, can't be one of the previous numbers.

<script type="text/javascript">
const numb = new Array();
for (var i = 0; i < 6; i++) {
numb[i] = Math.floor(49 * Math.random()) + 1;

//compare to existing numbs
for (var k = 0; k < numb.length - 1; k++) {
if (numb[i] == numb[k]) {
i--;
break;
}
}
}

let supNumb = new Array();
supNumb = Math.floor(49 * Math.random()) + 1;
for (var s = 0; s <= 1; s++) {
// compare supNumb to numb
for (var t = 0; t < numb.length - 1; t++) {
if (supNumb == numb[t]) {
s--;
break;
}
}
}


// SORT & DISPLAY NUMBERS
function sort(a, b) {
return a - b;
}

numb.sort(sort);
document.write("<p> " + numb);
document.write("<h4>" + "SuperSeven: " + supNumb);
</script>


I know by trying the super-seven
supNumb
is still giving out same numbers as in
numb
.

I can't get it to work and can't find anywhere this being mentioned.

Somebody here can look over it and let me know how I can compare
supNumb
to
numb
?

Is this even the right structure?

Thanks in advance!

Answer Source

You can make an infinit loop and break it if you find a valid number like so:

while(true){
    supNumb = Math.floor(49 * Math.random()) + 1;
    if(numb.indexOf(supNumb) < 0){
        break;
    }
}

Also better use indexOf so search in the array. It is much faster than plain JS. https://www.w3schools.com/jsref/jsref_indexof_array.asp


You could even use the Set mechanics to achieve this. Sets can only store unique values. All duplicates will thereby be ignored:

var numbers = new Set(),
    supNumb = 0;
while(numbers.size < 6){
    numbers.add(Math.floor(49 * Math.random()) + 1);
}
while(true){
    supNumb = Math.floor(49 * Math.random()) + 1;
    if(!numbers.has(supNumb)) break;
}
var sortedNumbers = [...numbers].sort((a,b)=>{return a-b})
console.log(sortedNumbers, supNumb);

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Set

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download