Random Ranges and Shuffling
Bounded randoms and collections shuffle.
Ranges and Shuffling
Real programs rarely want 0 to bound-1. This lesson covers arbitrary ranges, randomly shuffling collections, and picking random elements.
A Custom Range Formula
To produce an int from min to max inclusive, use min + rng.nextInt(max - min + 1).
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rng = new Random();
int min = 10, max = 20;
int value = min + rng.nextInt(max - min + 1);
System.out.println("10 to 20: " + value);
}
}All lessons in this course
- The Math Class
- Generating Random Numbers
- Random Ranges and Shuffling
- Math Rounding and Limits