I’m trying to generate 5 unique random numbers between two numbers. The sixth number is a random number between another set of numbers but it doesn’t have to be unique. I tried to ensure the uniqueness of each number by placing the first randomly generated number in an array.
Then each subsequent randomly generated number is checked against the numbers in this array. Any generated number matching a number in the array will be discarded and a new one is generated until one that doesn’t match any in the array is is found. My code doesn’t work because occasionally it produces duplicates.
How is this fixed?
https://jsfiddle.net/L3h0rf5q/
var btnGen = document.getElementById('generate');
var fiveNum = document.getElementById('fiveNums');
var lastNum = document.getElementById('lastNum');
btnGen.addEventListener('click', function () {
let ranNum;
let firstFive = "";
let pb = "";
let oldNum;
ranNum = GenerateNumbers();
ranNum.sort(
(a, b) => {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
);
for(let i=0; i<ranNum.length; i++){
if(i<ranNum.length - 1){
if(ranNum[i].toString().length<2){
firstFive += "0" + ranNum[i].toString() + " " + " " + " " + " " + " " + " "
}else{
firstFive += ranNum[i].toString() + " " + " " + " " + " " + " " + " "
}
}else{
if(ranNum[i].toString().length<2){
pb = "0" + ranNum[i].toString();
}else {
pb = ranNum[i].toString();
}
}
fiveNum.innerHTML = firstFive;
lastNum.innerHTML = pb;
}
});
function GenerateNumbers() {
let randomNums = [];
let selectedNums = [];
let newNum = undefined;
for (let i = 0; i < 6; i++) {
if (i == 0) {
newNum = Math.floor(Math.random() * 75) + 1
randomNums[i] = newNum;
selectedNums.push(newNum);
}
if (i >0 && i < 5){
while (selectedNums.includes(newNum)) {
newNum = Math.floor(Math.random() * 75) + 1
}
randomNums[i] = newNum;
//add to an array
selectedNums.push(newNum);
}
if (i == 5) {
randomNums[i] = Math.floor(Math.random() * 42) + 1
}
}
return randomNums;
}
<div style="margin-left:20%; width:500px; font-weight:bold; font-size:30px;">
<button id="generate" style="margin-left:36%">Generate Numbers</button>
<br><br>
<div>
<label style="margin-left:20%">Generate Numbers</label>
<br>
<div style="background-color:black">
<span id="fiveNums" style="margin-left: 10%; width:80%; color:blue;"></span>
<span id="lastNum" style="color:blue;"></span>
</div>
</div>
Aucun commentaire:
Enregistrer un commentaire