I am trying to make a Random Number Generator.
I made a code and it does work well.
document.querySelector('#btn').addEventListener('click',()=>{
generate(1,45,6)
});
function generate(min, max, count){
const arr = [];
if(min >= max) return;
if(max - min + 1 < count) return;
while (arr.length < count) {
let num = Math.floor(Math.random() * max) + min;
let flag = arr.every((i) => {
return i === num ? false : true;
});
if (flag) {
arr.push(num);
}
}
console.log(arr);
}
<button id="btn">Gen</button>
But my algorithm's time complexity is O(n).
I hope to reduce the time complexity if I can.
And, I guess my above code can be compacted, but I can't.
Summary What I Want
-
To reduce the time complexity if it can be
-
To make it compacted
Aucun commentaire:
Enregistrer un commentaire