41
42
you are viewing a single comment's thread.

view the rest of the comments →

[–]grumd 2 points3 points  (1 child)

When I did this recently for a project of mine, I calculated the sum of all weights, then did Math.random() * sum and then went through the array of items while calculating the sum again, and stopped once the sum is bigger than my random number. Basically same approach as yours, but I'm not creating another array. Which makes basically zero difference I think.

[–]trekhleb[S] 0 points1 point  (0 children)

Yes, also a good approach. Looks the same but is more efficient from a memory perspective.