### Problem

Given a number x, less than 100. How will you generate true with probability x/100. So if x = 65, how will you generate true with probability 65/100. You can represent true by 1 and false by 0.### Solution

We can make use of rand() function to generate a number less than 100 by taking rand()%100. If the number is less than x, you can output true, otherwise you output false.If you are asked to generate true x times, then you use the same logic to generate true or false with probability x/100 and 1 - x/100 and keep recording the number of true and false. Eventually either all true or all false, will have come up and then you can simply output the remaining true or false.

Here is the code

public static void main(String[] args) { int x = 5; // write a function to generate true with a probability of 65/100 for (int i = 0; i < 10; i++) { System.out.println(generateTrue(x)); } } public static boolean generateTrue(int x) { double random = Math.random() * 100; if (random < x) { return true; } else { return false; } }

**References**

## 0 comments:

## Post a Comment