I am using the following code which generates random number between 0 to Totalfriends, I would like to get the random numbers but they should not be repeated. Any idea how?
This is the code I am using
FB.getLoginStatus(function(response) {
var profilePicsDiv = document.getElementById('profile_pics');
FB.api({ method: 'friends.get' }, function(result) {
// var result =resultF.data;
// console.log(result);
var user_ids="" ;
var totalFriends = result.length;
// console.log(totalFriends);
var numFriends = result ? Math.min(25, result.length) : 0;
// console.log(numFriends);
if (numFriends > 0) {
for (var i=0; i<numFriends; i++) {
var randNo = Math.floor(Math.random() * (totalFriends + 1))
user_ids+= (',' + result[randNo]);
console.log(user_ids);
}
}
profilePicsDiv.innerHTML = user_ids;
});
});
yourarray
) of numbers in range[1..totalfriends]
Fisher-Yates
algorithm)for
(from0
toyourarray.length - 1
) make apop()
from the array (or just get then-th
element) so you will get everytime a different numberDoing so you you will avoid to get duplicated numbers
I would perform random iterations, create an array with all your numbers in, such as:
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.
You're essentially shuffling them, and the result is going to give you the numbers in a random order.
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 thearray
argument.Assuming your code works how I think it does, you already have an array of userids:
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
This should work fine.