Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test case of randx.RandomIntWeight not correct in go playground https://go.dev/play/p/XiLXecuRZDc #5

Closed
leopku opened this issue Jan 27, 2022 · 2 comments

Comments

@leopku
Copy link

leopku commented Jan 27, 2022

First of all, thanks for this awesome library.

Result running in playground is 1
But result of same code running in my laptop is 2

BTW, I am not exactly know when to use RandomIntWeight func

@icza
Copy link
Owner

icza commented Jan 27, 2022

Please read the doc of the function: https://pkg.go.dev/github.com/icza/gox/mathx/randx#RandomIntWeight

RandomIntWeight chooses an index randomly using the listed non-negative relative weights.

The default Rand of math/rand package is used for random data.

Implementation guarantees to return an integer in the range of [0..len(weights)). If no weight is provided or they add up to 0, -1 is returned. Behavior for negative weights is undefined.

So for example if you pass [2, 1], then an index either 0 or 1 will be returned, and 0 will be returned with twice the probability that of 1, because the first number you pass is double that of the second.

Similarly, if you pass [5, 3, 2], then an index either of 0, 1 or 2 will be returned; 0 will be returned with 50% chance, 1 will be returned with 30% chance and 2 will be returned with 20% chance.

The returned index is chosen randomly, and varies from call to call. Also note that you must seed the rand package properly, e.g. with rand.Seed(time.Now().UnixNano()).

Also note that the output of the Go Playground is cached, and the time on the Playground is fixed (meaning test it on your computer).

@leopku
Copy link
Author

leopku commented Jan 28, 2022

@icza Got it. Thanks for your reply.

@leopku leopku closed this as completed Jan 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants