How could I implement random item selection by weight?

I added game chest to my game and I want the server to select random items depending on the weight (probability ) of the item

I found this package

How can I use it? My issue is with caching it globally like this. Is this fine?

var chooser *wr.chooser

Do I need to use Redis or Memcached?

Hey @mohammed I’d write a Nakama runtime server RPC that makes a call to our storage collections Collections - Nakama server to fetch the weighted table and then run the algorithm exported by the package you found on the contents fetched. I don’t think there’s a need to store it in a global golang variable since the data is persisted by our storage engine and the computation is local to the RPC.

1 Like


The developer mentioned this point

Don’t be mislead by these numbers into thinking weightedrand is always the right choice! If you are only picking from the same distribution once, randutil will be faster. weightedrand optimizes for repeated calls at the expense of some initialization time and memory storage.

For real game the requests for opening chest will be continuous. So, to avoids a significant amount of database IO overhead getting same common data f by all players.

@Mohammed storing the chooser as a global variable should be fine if it’s a thread-safe object.

1 Like