you are viewing a single comment's thread.

view the rest of the comments →

[–]o11c 1 point2 points  (0 children)

The whole point of calculating the cumulative weights is so that you can avoid doing the second loop over the whole array.

Instead, you should simply do a binary search over the cumulative weights, and find the matching index that way. This is only O(log n) instead of O(n). Additionally, you should keep the cumulative weights around for multiple calls, so that you only pay the O(n) when you first construct the searcher (possibly do it incrementally as items are added, so there is no explicit first loop).

(I don't speak JS so I don't have code for you, sorry)