jeudi 30 septembre 2021

What is the most efficient way to generate random numbers from a union of disjoint ranges in Kotlin?

I would like to generate random numbers from a union of ranges in Kotlin. I know I can do something like

((1..10) + (50..100)).random()

but unfortunately this creates an intermediate list, which can be rather expensive when the ranges are large.

I know I could write a custom function to randomly select a range with a weight based on its width, followed by randomly choosing an element from that range, but I am wondering if there is a cleaner way to achieve this with Kotlin built-ins.




Aucun commentaire:

Enregistrer un commentaire