Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: do something x percent of the time

Tags:

I need a few lines of Java code that run a command x percent of the time at random.

psuedocode:

boolean x = true 10% of cases.

if(x){
  System.out.println("you got lucky");
}
like image 684
John R Avatar asked Apr 01 '11 17:04

John R


People also ask

Can you use percentage in Java?

In Java, the modulus operator is a percent sign, %. The syntax is the same as for other operators: int quotient = 7 / 3; int remainder = 7 % 3; The first operator, integer division, yields 2.

How do you find 50 percent of a number in Java?

int k = (int)(120 / 100)*50; The above does not work because you are performing an integer division expression (120 / 100) which result is integer 1, and then multiplying that result to 50, giving the final result of 50.

How do you show percentage in Java?

With this formatter, a decimal fraction such as 0.75 is displayed as 75%. The following code sample shows how to format a percentage. Double percent = new Double(0.75); NumberFormat percentFormatter; String percentOut; percentFormatter = NumberFormat.

Why do we use percentage in Java?

It has a special meaning in JavaScript: it's the remainder operator. It obtains the remainder between two numbers. This is different from languages like Java, where % is the modulo operator.


3 Answers

You just need something like this:

Random rand = new Random();  if (rand.nextInt(10) == 0) {     System.out.println("you got lucky"); } 

Here's a full example that measures it:

import java.util.Random;  public class Rand10 {     public static void main(String[] args) {         Random rand = new Random();         int lucky = 0;         for (int i = 0; i < 1000000; i++) {             if (rand.nextInt(10) == 0) {                 lucky++;             }         }         System.out.println(lucky); // you'll get a number close to 100000     } } 

If you want something like 34% you could use rand.nextInt(100) < 34.

like image 173
WhiteFang34 Avatar answered Sep 19 '22 01:09

WhiteFang34


If by time you mean times that the code is being executed, so that you want something, inside a code block, that is executed 10% of the times the whole block is executed you can just do something like:

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 this works by average usage. You won't get near to 10% unless yourFunction() is called a reasonable amount of times.

like image 32
Jack Avatar answered Sep 21 '22 01:09

Jack


To take your code as a base, you could simply do it like that:

if(Math.random() < 0.1){
  System.out.println("you got lucky");
}

FYI Math.random() uses a static instance of Random

like image 31
Crystark Avatar answered Sep 17 '22 01:09

Crystark