How to generate random numbers with no repeat javascript

℡╲_俬逩灬. 提交于 2019-11-28 02:17:17

Here's a function that will take n random elements from array, and return them, based off a fisher-yates shuffle. Note that it will modify the array argument.

function randomFrom(array, n) {
    var at = 0;
    var tmp, current, top = array.length;

    if(top) while(--top && at++ < n) {
        current = Math.floor(Math.random() * (top - 1));
        tmp = array[current];
        array[current] = array[top];
        array[top] = tmp;
    }

    return array.slice(-n);
}

Assuming your code works how I think it does, you already have an array of userids:

var random10 = randomFrom(friendIds, 10);
  1. create an array (e.g. yourarray) of numbers in range [1..totalfriends]
  2. shuffle the array (e.g. using a javascript implementation of Fisher-Yates algorithm)
  3. inside the for (from 0 to yourarray.length - 1) make a pop() from the array (or just get the n-th element) so you will get everytime a different number

Doing so you you will avoid to get duplicated numbers

I would perform random iterations, create an array with all your numbers in, such as:

var friendIndexes = [];

for (var i=0; i<numFriends; i++)
{
   friendIndexes.push(i);
}

Then once you have an array of all the numbers, I would perform some number of iterations, maybe 1,000, where you generate two random numbers, and swap the values in those indexes.

for (var s = 0; s<1000; s++)
{
    var rnd1 = Math.floor(Math.random() * (numFriends + 1);
    var rnd2 = Math.floor(Math.random() * (numFriends + 1);

    // Swap the two values (remember to use a temp variable)
    var tmp = friendIndexes[rnd1];
    friendIndexes[rnd1] = friendIndexes[rnd2];
    friendIndexes[rnd2] = tmp;
}

You're essentially shuffling them, and the result is going to give you the numbers in a random order.

Take a big number wich not divide numFriends or just a big prime number (like one : 702038, 727699, 992700, 1201046, 1232255, 2312734, 3136255, 4235414, 6090515) then goes

var result=[] ;
var K=Math.floor((Math.random()*bigUnNumFreindsDivider) ;

for (var i=0; i<numFriends; i++)
{
    result[i]=(i*bigUnNumFreindsDivider+K)%numFreinds ;
}

This should work fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!