I have an array, lets say :
var people = [
{name: "Jack", weight: 10},
{name: "Beth",weight: 2},
{name: "Michael",weight: 5},
{name: "Elsa",weight: 6},
{name: "April",weight: 3},
{name: "John",weight: 6},
{name: "David",weight: 1}
]
And I want to pick from this list of objects, while picking some of them more often according to their weight.
I can do that with brute force by pushing each object into a seperate array as many times as their weight value.
eg: var newArr = ["Jack", "Jack", "Jack", ........, "John", "John", "David"];
But this is not an elegant and optimal way of doing things. Given a large number of objects, this solution does not provide a good peformance.
I want to create a function to select from the array, and run that function 100 times, or even 1000 times to check if the solution returns a desired distribution.
function selectVolunteer(arr) {
// some code here
return randomVolunteer;
}
// Now run the function 1000 times to check this works
for (var i = 0; i < 10000; i++) {
function selectVolunteer(people)
}
So, what are my options to create a more efficient algorithm, so that when i iterate through a list of 100000 objects there will be no problem.
While posting this, i looked at some questions suggested by StackOverflow, but could not find what i was looking for. There is an answer Generate A Weighted Random Number suggested by @trincot, but there are some conflicts with the question i asked. If i run that suggested function with these parameters
arr = {0:0.1, 1:0.7, 2:0.9}
10000 times, it gives me this output :0 : 983 , 1 : 7011 and 2 : 2006
which is all wrong because 2 has more probability than 1 while outout suggest something different.
Thank you.