Java: do sth in a period of time

I need a few lines of Java code to run x% at random

Pseudo code:

boolean x = true 10% of cases.

if(x){
  System.out.println("you got lucky");
}

Solution

If the number of code executions is expressed by time, you want to execute 10% of the execution time of the whole program segment within the code block. You can do the following:

Random r = new Random();

...
void yourFunction()
{
  float chance = r.nextFloat();

  if (chance <= 0.10f)
    doSomethingLucky();
}

Of course, 0.10f stands for 10%, but you can adjust it Like every PRNG algorithm, it is used by averaging You won't get close to 10% unless your function () is called a reasonable number of times

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>