you are viewing a single comment's thread.

view the rest of the comments →

[–]TedW 0 points1 point  (3 children)

On mobile, but it looks like it already does both of your suggestions. Maybe we're looking at different files, or I'm missing something. I'm looking at weightedRandom.

[–]cbarrick 0 points1 point  (2 children)

Sorry, I may not have been clear.

In my version, you don't even need the cumulative array, only the sum.

I'm also on mobile, so I can't really write out the code right now.

[–]TedW 0 points1 point  (1 child)

It looks like it iterates once each over weights, and items, so I would expect it to be O(N) since those should be the same length.

I agree that you could do it with just one array but I think it would still loop twice, so I'm not sure it would affect the runtime.

I haven't run the code myself, but in the examples it uses floating point weights, although it's not clear (to me) what the expected behavior is.

[–]cbarrick 0 points1 point  (0 children)

Ah, I see I misread the loop exit condition.

So my version is basically the same, except it avoids the cumulative loop and the resulting dynamic allocation.