the problem with random generations of objects closed

For simplicity’s sake, you could use the output of a Math.random() call, which returns a random double greater than or equal to 0.0 and less than 1.0. Simply checking whether it returns a value less than or equal to your frequency (0.1) would do the trick


boolean randomGenerate = (Math.random() < 0.1);

randomGenerate shall be assigned true only 10% of the time.

As for your second problem, assuming you are using a 2d array as your board, you can randomly generate int array index. As I said earlier, Math.random() returns a double, D such that 0.0 ≤ D < 1.0. Multiplying that by 5 would give you a double D such that 0.0 ≤ D < 5.0. Casting that double to int would return you an int between 0 and 4. Example:

int randomIndex = (int) (Math.random() * 5);

randomIndex shall take any value from the set {0,1,2,3,4} with equal probability.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top