Search code examples
kotlinprobability

Get boolean distributed by a given discrete probability


I currently have a discrete probability that I calculated earlier. I'm getting it like this, so it's just a straightforward double between 0 and 1, which describes the possibility that a certain event will happen. The higher the level, the lower the probability is for this event to actually take place.

val chanceOfLosingDura = 1/(unbreakingLevel+1)

I now need a boolean, and every time my code is called, a new one should be generated. The probability for it to be true should be chanceOfLosingDura.

I know how to basically approach this. I could just get a list of 100 booleans, of which chanceOfLosingDura * 100 will be true, and otherwise false, and then draw a random element of that list. However I'm pretty sure that there's a cleaner way to do this in Kotlin, am I right?


Solution

  • The simplest solution would be to generate a random value between 0 and 1 and check if it's greater than chanceOfLosingDura:

    val random = Random(System.currentTimeMillis())
    ...
    val value = random.nextDouble(1.0) > chanceOfLosingDura
    

    It's not 100% accurate, but maybe good enough. When I run it 100000 times for chanceOfLosingDura == 0.9, I got 10008 times true, i.e probability of false was 0.89992