samedi 24 novembre 2018

Generate Random elements without duplicate

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

  1. To reduce the time complexity if it can be

  2. To make it compacted




Aucun commentaire:

Enregistrer un commentaire