Search code examples
algorithmpseudocode

How to compute the "15% of the time" randomness?


I'm looking for a decent, elegant method of calculating this simple logic.
Right now I can't think of one, it's spinning my head.

I am required to do some action only 15% of the time.

I'm used to "50% of the time" where I just mod the milliseconds of the current time and see if it's odd or even, but I don't think that's elegant.

How would I elegantly calculate "15% of the time"? Random number generator maybe?
Pseudo-code or any language are welcome.

Hope this is not subjective, since I'm looking for the "smartest" short-hand method of doing that.

Thanks.


Solution

  • Solution 1 (double)

    • get a random double between 0 and 1 (whatever language you use, there must be such a function)
    • do the action only if it is smaller than 0.15

    Solution 2 (int)

    You can also achieve this by creating a random int and see if it is dividable to 6 or 7. UPDATE --> This is not optimal.