W
W
WarriorKodeK2018-02-26 18:36:58
JavaScript
WarriorKodeK, 2018-02-26 18:36:58

How to generate numbers?

Hello.
Let's say I have the number 40. I need to generate a random number from 1 to 40 every 2 seconds, while it is necessary that the numbers do not repeat, how can this be done?
Here is my generation code.

const generateRandomNums = (max = 40) => {
  return Math.floor(Math.random() * (max - 1 + 1)) + 1;
};

var timerId = setInterval(() => {
  console.log(generateRandomNums());
}, 2000);

My thought:
Create an array, and before generating it, check whether there is that number in it, if so, then go to the next one. "iteration", if not, then push the number into an array and show it to the console.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2018-02-26
@WarriorKodeK

Let's generate a generator !

function* rnd(n) {
  var nums = [], i, randomIndex, itemAtIndex;
  for( i=0; i<n; nums.push(i++));
  for( i=n-1; i>=0; i--) {
    randomIndex = Math.floor(Math.random()*(i+1)); 
    itemAtIndex = nums[randomIndex]; 
    nums[randomIndex] = nums[i]; 
    nums[i] = itemAtIndex;
  }
  i = n - 1
  while(i >= 0)
    yield nums[i--];
}


var gen = rnd(10);

while(true) {
  var v = gen.next();
  if( v.done) break;
  console.log(v.value);
}
console.log('Done!');

M
Maxim Timofeev, 2018-02-26
@webinar

we make an array with numbers, read the number of array elements, pull a random key, while removing this value from the array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question