Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
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!');
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 questionAsk a Question
731 491 924 answers to any question