Generate Array of Random AND unique Numbers in JavaScript #shorts

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

you can use a Set and iterate while .size is not equal to count then return Array.from(set.values()), with this approach you don't need to check if number already exists

ursochurrasqueira
Автор

You probably also want to make sure count < max if count is 20 and max is 5 you can’t get 20 unique numbers between 0 and 5 and so you’ll infinite loop

brandonmyers
Автор

IndexOf() has O(n) time complexity rather can I use objects as hash tables to get O(1) time complexity?

shahriajamankhan
Автор

It will be nice if there will be fi statement which checks if count is greater than max, if so function should stop, otherwise while loop becomes infinite. also the function needs some optimizations when count is very close to max, otherwise it could also have infinite loop effect

peoplearecool
Автор

Why not generate a list of nums to the max and then pop a random index? I assume that looking up whether a number exists on every iteration is quite expensive. As long as the max isn’t absurdly big I think the memory usage is bearable.

electricCoookie
Автор

I feel like this would have been better done via generator function returning an interator.
And for-i loop would have been faster. According to my profiling about 100% faster.

Speaking strictly towards optimization, an iterarator would have been far better.
Handy with a spread operator, or Array.from... or if you're feeling specific you could just use it as an interator and utilize the built-in next() method.

asteinerd
Автор

Hey, what would be a solution for count = and what would be the time complexity in this case?

alenamitnovizki
Автор

This has an issue. What if the count is 5 and max number is also 5! It will work, but not efficiently. Other than that, if count is 5 and max number is less than 5, it will be an infinite while loop.

md.sorifulislamchanchal
Автор

Includes is cleaner to me any reasons not to use it ?

Shabztubeyou
Автор

i = 1;
while(i <= 5){
randNum = Math.floor(Math.random() * 10);
!== -1){
continue;
}
uniqueRands.push(randNum);
i++;

}
console.log(uniqueRands)

khuramshahzad