When building games that need dice rolls, simulations that require random sampling, or tests that need varied input data, you need controlled randomness. Java's Random class generates pseudo-random numbers with optional seeding for reproducible sequences.

Pseudo-random Numbers generated by a deterministic algorithm that appear random but are reproducible when given the same seed.

Basic Usage

Create a Random instance and generate numbers.

seed
Basic.java
Replay: real traced execution (multi-file project)
// Create and use Random

import java.util.Random;

public class Basic {
    public static void main(String[] args) {
        // Create Random with a seed for reproducible output
        int seed = 42;
        Random rand = new Random(seed);
        System.out.println("Seed: " + seed);

        // Random integers
        System.out.println("Random integers:");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + rand.nextInt());
        }

        // Random integers in range [0, bound)
        System.out.println("\nRandom int [0, 100):");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + rand.nextInt(100));
        }

        // Random doubles [0.0, 1.0)
        System.out.println("\nRandom doubles:");
        for (int i = 0; i < 5; i++) {
            System.out.printf("  %.6f%n", rand.nextDouble());
        }

        // Random booleans
        System.out.println("\nRandom booleans:");
        for (int i = 0; i < 10; i++) {
            System.out.print(rand.nextBoolean() ? "T " : "F ");
        }
        System.out.println();

        // Random longs
        System.out.println("\nRandom longs:");
        for (int i = 0; i < 3; i++) {
            System.out.println("  " + rand.nextLong());
        }

        // Random floats
        System.out.println("\nRandom floats:");
        for (int i = 0; i < 5; i++) {
            System.out.printf("  %.6f%n", rand.nextFloat());
        }

        // Gaussian (normal) distribution
        System.out.println("\nGaussian (mean=0, stddev=1):");
        for (int i = 0; i < 10; i++) {
            System.out.printf("  %.4f%n", rand.nextGaussian());
        }

        // Seeded Random (reproducible)
        System.out.println("\nSeeded Random (seed=" + seed + "):");
        Random seeded1 = new Random(seed);
        Random seeded2 = new Random(seed);

        System.out.println("First sequence:");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + seeded1.nextInt(100));
        }

        System.out.println("Second sequence (same):");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + seeded2.nextInt(100));
        }

        // Separate Random instance for independent sequence
        System.out.println("\nSeparate seeded Random:");
        Random separate = new Random(seed + 1);
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + separate.nextInt(100));
        }

        // Random.nextDouble() for decimal values
        System.out.println("\nRandom.nextDouble():");
        for (int i = 0; i < 5; i++) {
            double r = rand.nextDouble();  // [0.0, 1.0)
            System.out.printf("  %.6f%n", r);
        }

        // Custom range using Random.nextDouble()
        System.out.println("\nRandom.nextDouble() in range [10, 20):");
        for (int i = 0; i < 5; i++) {
            int min = 10;
            int max = 20;
            int r = (int)(rand.nextDouble() * (max - min)) + min;
            System.out.println("  " + r);
        }

        // nextBytes
        System.out.println("\nRandom bytes:");
        byte[] bytes = new byte[10];
        rand.nextBytes(bytes);
        for (byte b : bytes) {
            System.out.printf("%3d ", b);
        }
        System.out.println();
    }

    //help h1
    // new Random(seed) - create reproducible random number generator
    // new Random(seed) - reproducible sequence
    // .nextInt() - random int
    // .nextInt(bound) - [0, bound)
    // .nextDouble() - [0.0, 1.0)
    // .nextBoolean() - true or false
    // .nextGaussian() - normal distribution
    // rand.nextDouble() - decimal [0.0, 1.0)
    //end
}
// Create and use Random

import java.util.Random;

public class Basic {
    public static void main(String[] args) {
        // Create Random with a seed for reproducible output
        int seed = 7;
        Random rand = new Random(seed);
        System.out.println("Seed: " + seed);

        // Random integers
        System.out.println("Random integers:");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + rand.nextInt());
        }

        // Random integers in range [0, bound)
        System.out.println("\nRandom int [0, 100):");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + rand.nextInt(100));
        }

        // Random doubles [0.0, 1.0)
        System.out.println("\nRandom doubles:");
        for (int i = 0; i < 5; i++) {
            System.out.printf("  %.6f%n", rand.nextDouble());
        }

        // Random booleans
        System.out.println("\nRandom booleans:");
        for (int i = 0; i < 10; i++) {
            System.out.print(rand.nextBoolean() ? "T " : "F ");
        }
        System.out.println();

        // Random longs
        System.out.println("\nRandom longs:");
        for (int i = 0; i < 3; i++) {
            System.out.println("  " + rand.nextLong());
        }

        // Random floats
        System.out.println("\nRandom floats:");
        for (int i = 0; i < 5; i++) {
            System.out.printf("  %.6f%n", rand.nextFloat());
        }

        // Gaussian (normal) distribution
        System.out.println("\nGaussian (mean=0, stddev=1):");
        for (int i = 0; i < 10; i++) {
            System.out.printf("  %.4f%n", rand.nextGaussian());
        }

        // Seeded Random (reproducible)
        System.out.println("\nSeeded Random (seed=" + seed + "):");
        Random seeded1 = new Random(seed);
        Random seeded2 = new Random(seed);

        System.out.println("First sequence:");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + seeded1.nextInt(100));
        }

        System.out.println("Second sequence (same):");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + seeded2.nextInt(100));
        }

        // Separate Random instance for independent sequence
        System.out.println("\nSeparate seeded Random:");
        Random separate = new Random(seed + 1);
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + separate.nextInt(100));
        }

        // Random.nextDouble() for decimal values
        System.out.println("\nRandom.nextDouble():");
        for (int i = 0; i < 5; i++) {
            double r = rand.nextDouble();  // [0.0, 1.0)
            System.out.printf("  %.6f%n", r);
        }

        // Custom range using Random.nextDouble()
        System.out.println("\nRandom.nextDouble() in range [10, 20):");
        for (int i = 0; i < 5; i++) {
            int min = 10;
            int max = 20;
            int r = (int)(rand.nextDouble() * (max - min)) + min;
            System.out.println("  " + r);
        }

        // nextBytes
        System.out.println("\nRandom bytes:");
        byte[] bytes = new byte[10];
        rand.nextBytes(bytes);
        for (byte b : bytes) {
            System.out.printf("%3d ", b);
        }
        System.out.println();
    }

    //help h1
    // new Random(seed) - create reproducible random number generator
    // new Random(seed) - reproducible sequence
    // .nextInt() - random int
    // .nextInt(bound) - [0, bound)
    // .nextDouble() - [0.0, 1.0)
    // .nextBoolean() - true or false
    // .nextGaussian() - normal distribution
    // rand.nextDouble() - decimal [0.0, 1.0)
    //end
}
// Create and use Random

import java.util.Random;

public class Basic {
    public static void main(String[] args) {
        // Create Random with a seed for reproducible output
        int seed = 12345;
        Random rand = new Random(seed);
        System.out.println("Seed: " + seed);

        // Random integers
        System.out.println("Random integers:");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + rand.nextInt());
        }

        // Random integers in range [0, bound)
        System.out.println("\nRandom int [0, 100):");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + rand.nextInt(100));
        }

        // Random doubles [0.0, 1.0)
        System.out.println("\nRandom doubles:");
        for (int i = 0; i < 5; i++) {
            System.out.printf("  %.6f%n", rand.nextDouble());
        }

        // Random booleans
        System.out.println("\nRandom booleans:");
        for (int i = 0; i < 10; i++) {
            System.out.print(rand.nextBoolean() ? "T " : "F ");
        }
        System.out.println();

        // Random longs
        System.out.println("\nRandom longs:");
        for (int i = 0; i < 3; i++) {
            System.out.println("  " + rand.nextLong());
        }

        // Random floats
        System.out.println("\nRandom floats:");
        for (int i = 0; i < 5; i++) {
            System.out.printf("  %.6f%n", rand.nextFloat());
        }

        // Gaussian (normal) distribution
        System.out.println("\nGaussian (mean=0, stddev=1):");
        for (int i = 0; i < 10; i++) {
            System.out.printf("  %.4f%n", rand.nextGaussian());
        }

        // Seeded Random (reproducible)
        System.out.println("\nSeeded Random (seed=" + seed + "):");
        Random seeded1 = new Random(seed);
        Random seeded2 = new Random(seed);

        System.out.println("First sequence:");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + seeded1.nextInt(100));
        }

        System.out.println("Second sequence (same):");
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + seeded2.nextInt(100));
        }

        // Separate Random instance for independent sequence
        System.out.println("\nSeparate seeded Random:");
        Random separate = new Random(seed + 1);
        for (int i = 0; i < 5; i++) {
            System.out.println("  " + separate.nextInt(100));
        }

        // Random.nextDouble() for decimal values
        System.out.println("\nRandom.nextDouble():");
        for (int i = 0; i < 5; i++) {
            double r = rand.nextDouble();  // [0.0, 1.0)
            System.out.printf("  %.6f%n", r);
        }

        // Custom range using Random.nextDouble()
        System.out.println("\nRandom.nextDouble() in range [10, 20):");
        for (int i = 0; i < 5; i++) {
            int min = 10;
            int max = 20;
            int r = (int)(rand.nextDouble() * (max - min)) + min;
            System.out.println("  " + r);
        }

        // nextBytes
        System.out.println("\nRandom bytes:");
        byte[] bytes = new byte[10];
        rand.nextBytes(bytes);
        for (byte b : bytes) {
            System.out.printf("%3d ", b);
        }
        System.out.println();
    }

    //help h1
    // new Random(seed) - create reproducible random number generator
    // new Random(seed) - reproducible sequence
    // .nextInt() - random int
    // .nextInt(bound) - [0, bound)
    // .nextDouble() - [0.0, 1.0)
    // .nextBoolean() - true or false
    // .nextGaussian() - normal distribution
    // rand.nextDouble() - decimal [0.0, 1.0)
    //end
}
  1. seed ← 42, rand ← ⟨Random A⟩

    5public class Basic {6    public static void main(String[] args) {7        // Create Random with a seed for reproducible output8        int seed→ 42 = 42; //@seed=7, 123459        Random rand→ ⟨Random A⟩ = new Random(seed);10        System.out.println("Seed: " + seed42);11        12        // Random integers13        System.out.println("Random integers:");14        for (int i = 0; i < 5; i++) {
    outputSeed: 42
    Random integers:
  2. for (int i = 0; i < 5; i++)

    pass 1 of 5
    13System.out.println("Random integers:");14for (int i0 = 0; i < 5; i++) {15    System.out.println("  " + rand.nextInt());16}
    output  -1170105035
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  3. System.out.println(" Random int [0, 100):");

    18// Random integers in range [0, bound)19System.out.println("\nRandom int [0, 100):");20for (int i = 0; i < 5; i++) {
    output
    Random int [0, 100):
  4. for (int i = 0; i < 5; i++)

    pass 1 of 5
    19System.out.println("\nRandom int [0, 100):");20for (int i0 = 0; i < 5; i++) {21    System.out.println("  " + rand.nextInt(100));22}
    output  25
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  5. System.out.println(" Random doubles:");

    24// Random doubles [0.0, 1.0)25System.out.println("\nRandom doubles:");26for (int i = 0; i < 5; i++) {
    output
    Random doubles:
  6. for (int i = 0; i < 5; i++)

    pass 1 of 5
    25System.out.println("\nRandom doubles:");26for (int i0 = 0; i < 5; i++) {27    System.out.printf("  %.6f%n", rand.nextDouble());28}
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  7. System.out.println(" Random booleans:");

    30// Random booleans31System.out.println("\nRandom booleans:");32for (int i = 0; i < 10; i++) {
    output
    Random booleans:
  8. for (int i = 0; i < 10; i++)

    pass 1 of 10
    31System.out.println("\nRandom booleans:");32for (int i0 = 0; i < 10; i++) {33    System.out.print(rand.nextBoolean() ? "T " : "F ");34}
    outputT 
    All 10 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
    98
    109
  9. System.out.println();

    34}35System.out.println();3637// Random longs38System.out.println("\nRandom longs:");39for (int i = 0; i < 3; i++) {
    output
    Random longs:
  10. for (int i = 0; i < 3; i++)

    pass 1 of 3
    38System.out.println("\nRandom longs:");39for (int i0 = 0; i < 3; i++) {40    System.out.println("  " + rand.nextLong());41}
    output  -7482923245497525943
    All 3 passes — pass 1 is the card above
    passi
    10
    21
    32
  11. System.out.println(" Random floats:");

    43// Random floats44System.out.println("\nRandom floats:");45for (int i = 0; i < 5; i++) {
    output
    Random floats:
  12. for (int i = 0; i < 5; i++)

    pass 1 of 5
    44System.out.println("\nRandom floats:");45for (int i0 = 0; i < 5; i++) {46    System.out.printf("  %.6f%n", rand.nextFloat());47}
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  13. System.out.println(" Gaussian (mean=0, stddev=1):");

    49// Gaussian (normal) distribution50System.out.println("\nGaussian (mean=0, stddev=1):");51for (int i = 0; i < 10; i++) {
    output
    Gaussian (mean=0, stddev=1):
  14. for (int i = 0; i < 10; i++)

    pass 1 of 10
    50System.out.println("\nGaussian (mean=0, stddev=1):");51for (int i0 = 0; i < 10; i++) {52    System.out.printf("  %.4f%n", rand.nextGaussian());53}
    All 10 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
    98
    109
  15. seeded1 ← ⟨Random B⟩, seeded2 ← ⟨Random C⟩

    55// Seeded Random (reproducible)56System.out.println("\nSeeded Random (seed=" + seed42 + "):");57Random seeded1→ ⟨Random B⟩ = new Random(seed);58Random seeded2→ ⟨Random C⟩ = new Random(seed);5960System.out.println("First sequence:");61for (int i = 0; i < 5; i++) {
    output
    Seeded Random (seed=42):
    First sequence:
  16. for (int i = 0; i < 5; i++)

    pass 1 of 5
    60System.out.println("First sequence:");61for (int i0 = 0; i < 5; i++) {62    System.out.println("  " + seeded1.nextInt(100));63}
    output  30
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  17. System.out.println("Second sequence (same):");

    65System.out.println("Second sequence (same):");66for (int i = 0; i < 5; i++) {
    outputSecond sequence (same):
  18. for (int i = 0; i < 5; i++)

    pass 1 of 5
    65System.out.println("Second sequence (same):");66for (int i0 = 0; i < 5; i++) {67    System.out.println("  " + seeded2.nextInt(100));68}
    output  30
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  19. separate ← ⟨Random D⟩

    70// Separate Random instance for independent sequence71System.out.println("\nSeparate seeded Random:");72Random separate→ ⟨Random D⟩ = new Random(seed + 1);73for (int i = 0; i < 5; i++) {
    output
    Separate seeded Random:
  20. for (int i = 0; i < 5; i++)

    pass 1 of 5
    72Random separate = new Random(seed + 1);73for (int i0 = 0; i < 5; i++) {74    System.out.println("  " + separate.nextInt(100));75}
    output  56
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  21. System.out.println(" Random.nextDouble():");

    77// Random.nextDouble() for decimal values78System.out.println("\nRandom.nextDouble():");79for (int i = 0; i < 5; i++) {
    output
    Random.nextDouble():
  22. r ← 0.3784287179875597

    pass 1 of 5
    78System.out.println("\nRandom.nextDouble():");79for (int i0 = 0; i < 5; i++) {80    double r→ 0.3784287179875597 = rand.nextDouble();  // [0.0, 1.0)81    System.out.printf("  %.6f%n", r0.3784287179875597);82}
    All 5 passes — pass 1 is the card above
    passir
    100.3784287179875597
    210.13642362296961053
    320.4362829094329638
    430.6487936445670887
    540.6959691863162578
  23. System.out.println(" Random.nextDouble() in range [10, 20):");

    84// Custom range using Random.nextDouble()85System.out.println("\nRandom.nextDouble() in range [10, 20):");86for (int i = 0; i < 5; i++) {
    output
    Random.nextDouble() in range [10, 20):
  24. min ← 10, max ← 20, r ← 19

    pass 1 of 5
    85System.out.println("\nRandom.nextDouble() in range [10, 20):");86for (int i0 = 0; i < 5; i++) {87    int min→ 10 = 10;88    int max→ 20 = 20;89    int r→ 19 = (int)(rand.nextDouble() * (max20 - min10)) + min;90    System.out.println("  " + r19);91}
    output  19
    All 5 passes — pass 1 is the card above
    passiminmaxr
    10102019
    21102015
    32102010
    43102010
    54102017
  25. byte[] bytes = new byte[10];

    93// nextBytes94System.out.println("\nRandom bytes:");95byte[] bytes = new byte[10];96rand.nextBytes(bytes);97for (byte b : bytes) {
    output
    Random bytes:
  26. for (byte b : bytes)

    pass 1 of 10
    96rand.nextBytes(bytes);97for (byte b-97 : bytes) {98    System.out.printf("%3d ", b-97);99}
    All 10 passes — pass 1 is the card above
    passb
    1-97
    291
    3-31
    4-62
    5-57
    6-112
    7-45
    871
    9-128
    1026
  27. System.out.println();

    99    }100    System.out.println();101}
  1. seed ← 7, rand ← ⟨Random A⟩

    5public class Basic {6    public static void main(String[] args) {7        // Create Random with a seed for reproducible output8        int seed→ 7 = 7;9        Random rand→ ⟨Random A⟩ = new Random(seed);10        System.out.println("Seed: " + seed7);11        12        // Random integers13        System.out.println("Random integers:");14        for (int i = 0; i < 5; i++) {
    outputSeed: 7
    Random integers:
  2. for (int i = 0; i < 5; i++)

    pass 1 of 5
    13System.out.println("Random integers:");14for (int i0 = 0; i < 5; i++) {15    System.out.println("  " + rand.nextInt());16}
    output  -1156638823
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  3. System.out.println(" Random int [0, 100):");

    18// Random integers in range [0, bound)19System.out.println("\nRandom int [0, 100):");20for (int i = 0; i < 5; i++) {
    output
    Random int [0, 100):
  4. for (int i = 0; i < 5; i++)

    pass 1 of 5
    19System.out.println("\nRandom int [0, 100):");20for (int i0 = 0; i < 5; i++) {21    System.out.println("  " + rand.nextInt(100));22}
    output  54
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  5. System.out.println(" Random doubles:");

    24// Random doubles [0.0, 1.0)25System.out.println("\nRandom doubles:");26for (int i = 0; i < 5; i++) {
    output
    Random doubles:
  6. for (int i = 0; i < 5; i++)

    pass 1 of 5
    25System.out.println("\nRandom doubles:");26for (int i0 = 0; i < 5; i++) {27    System.out.printf("  %.6f%n", rand.nextDouble());28}
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  7. System.out.println(" Random booleans:");

    30// Random booleans31System.out.println("\nRandom booleans:");32for (int i = 0; i < 10; i++) {
    output
    Random booleans:
  8. for (int i = 0; i < 10; i++)

    pass 1 of 10
    31System.out.println("\nRandom booleans:");32for (int i0 = 0; i < 10; i++) {33    System.out.print(rand.nextBoolean() ? "T " : "F ");34}
    outputT 
    All 10 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
    98
    109
  9. System.out.println();

    34}35System.out.println();3637// Random longs38System.out.println("\nRandom longs:");39for (int i = 0; i < 3; i++) {
    output
    Random longs:
  10. for (int i = 0; i < 3; i++)

    pass 1 of 3
    38System.out.println("\nRandom longs:");39for (int i0 = 0; i < 3; i++) {40    System.out.println("  " + rand.nextLong());41}
    output  7058350309194143667
    All 3 passes — pass 1 is the card above
    passi
    10
    21
    32
  11. System.out.println(" Random floats:");

    43// Random floats44System.out.println("\nRandom floats:");45for (int i = 0; i < 5; i++) {
    output
    Random floats:
  12. for (int i = 0; i < 5; i++)

    pass 1 of 5
    44System.out.println("\nRandom floats:");45for (int i0 = 0; i < 5; i++) {46    System.out.printf("  %.6f%n", rand.nextFloat());47}
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  13. System.out.println(" Gaussian (mean=0, stddev=1):");

    49// Gaussian (normal) distribution50System.out.println("\nGaussian (mean=0, stddev=1):");51for (int i = 0; i < 10; i++) {
    output
    Gaussian (mean=0, stddev=1):
  14. for (int i = 0; i < 10; i++)

    pass 1 of 10
    50System.out.println("\nGaussian (mean=0, stddev=1):");51for (int i0 = 0; i < 10; i++) {52    System.out.printf("  %.4f%n", rand.nextGaussian());53}
    All 10 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
    98
    109
  15. seeded1 ← ⟨Random B⟩, seeded2 ← ⟨Random C⟩

    55// Seeded Random (reproducible)56System.out.println("\nSeeded Random (seed=" + seed7 + "):");57Random seeded1→ ⟨Random B⟩ = new Random(seed);58Random seeded2→ ⟨Random C⟩ = new Random(seed);5960System.out.println("First sequence:");61for (int i = 0; i < 5; i++) {
    output
    Seeded Random (seed=7):
    First sequence:
  16. for (int i = 0; i < 5; i++)

    pass 1 of 5
    60System.out.println("First sequence:");61for (int i0 = 0; i < 5; i++) {62    System.out.println("  " + seeded1.nextInt(100));63}
    output  36
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  17. System.out.println("Second sequence (same):");

    65System.out.println("Second sequence (same):");66for (int i = 0; i < 5; i++) {
    outputSecond sequence (same):
  18. for (int i = 0; i < 5; i++)

    pass 1 of 5
    65System.out.println("Second sequence (same):");66for (int i0 = 0; i < 5; i++) {67    System.out.println("  " + seeded2.nextInt(100));68}
    output  36
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  19. separate ← ⟨Random D⟩

    70// Separate Random instance for independent sequence71System.out.println("\nSeparate seeded Random:");72Random separate→ ⟨Random D⟩ = new Random(seed + 1);73for (int i = 0; i < 5; i++) {
    output
    Separate seeded Random:
  20. for (int i = 0; i < 5; i++)

    pass 1 of 5
    72Random separate = new Random(seed + 1);73for (int i0 = 0; i < 5; i++) {74    System.out.println("  " + separate.nextInt(100));75}
    output  64
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  21. System.out.println(" Random.nextDouble():");

    77// Random.nextDouble() for decimal values78System.out.println("\nRandom.nextDouble():");79for (int i = 0; i < 5; i++) {
    output
    Random.nextDouble():
  22. r ← 0.914050901118219

    pass 1 of 5
    78System.out.println("\nRandom.nextDouble():");79for (int i0 = 0; i < 5; i++) {80    double r→ 0.914050901118219 = rand.nextDouble();  // [0.0, 1.0)81    System.out.printf("  %.6f%n", r0.914050901118219);82}
    All 5 passes — pass 1 is the card above
    passir
    100.914050901118219
    210.04602627126135539
    320.011618108144987094
    430.9869525209966808
    540.324051006646354
  23. System.out.println(" Random.nextDouble() in range [10, 20):");

    84// Custom range using Random.nextDouble()85System.out.println("\nRandom.nextDouble() in range [10, 20):");86for (int i = 0; i < 5; i++) {
    output
    Random.nextDouble() in range [10, 20):
  24. min ← 10, max ← 20, r ← 13

    pass 1 of 5
    85System.out.println("\nRandom.nextDouble() in range [10, 20):");86for (int i0 = 0; i < 5; i++) {87    int min→ 10 = 10;88    int max→ 20 = 20;89    int r→ 13 = (int)(rand.nextDouble() * (max20 - min10)) + min;90    System.out.println("  " + r13);91}
    output  13
    All 5 passes — pass 1 is the card above
    passiminmaxr
    10102013
    21102013
    32102014
    43102010
    54102011
  25. byte[] bytes = new byte[10];

    93// nextBytes94System.out.println("\nRandom bytes:");95byte[] bytes = new byte[10];96rand.nextBytes(bytes);97for (byte b : bytes) {
    output
    Random bytes:
  26. for (byte b : bytes)

    pass 1 of 10
    96rand.nextBytes(bytes);97for (byte b-4 : bytes) {98    System.out.printf("%3d ", b-4);99}
    All 10 passes — pass 1 is the card above
    passb
    1-4
    2-18
    3-128
    4-18
    5-3
    67
    7-83
    865
    9101
    1083
  27. System.out.println();

    99    }100    System.out.println();101}
  1. seed ← 12345, rand ← ⟨Random A⟩

    5public class Basic {6    public static void main(String[] args) {7        // Create Random with a seed for reproducible output8        int seed→ 12345 = 12345;9        Random rand→ ⟨Random A⟩ = new Random(seed);10        System.out.println("Seed: " + seed12345);11        12        // Random integers13        System.out.println("Random integers:");14        for (int i = 0; i < 5; i++) {
    outputSeed: 12345
    Random integers:
  2. for (int i = 0; i < 5; i++)

    pass 1 of 5
    13System.out.println("Random integers:");14for (int i0 = 0; i < 5; i++) {15    System.out.println("  " + rand.nextInt());16}
    output  1553932502
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  3. System.out.println(" Random int [0, 100):");

    18// Random integers in range [0, bound)19System.out.println("\nRandom int [0, 100):");20for (int i = 0; i < 5; i++) {
    output
    Random int [0, 100):
  4. for (int i = 0; i < 5; i++)

    pass 1 of 5
    19System.out.println("\nRandom int [0, 100):");20for (int i0 = 0; i < 5; i++) {21    System.out.println("  " + rand.nextInt(100));22}
    output  84
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  5. System.out.println(" Random doubles:");

    24// Random doubles [0.0, 1.0)25System.out.println("\nRandom doubles:");26for (int i = 0; i < 5; i++) {
    output
    Random doubles:
  6. for (int i = 0; i < 5; i++)

    pass 1 of 5
    25System.out.println("\nRandom doubles:");26for (int i0 = 0; i < 5; i++) {27    System.out.printf("  %.6f%n", rand.nextDouble());28}
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  7. System.out.println(" Random booleans:");

    30// Random booleans31System.out.println("\nRandom booleans:");32for (int i = 0; i < 10; i++) {
    output
    Random booleans:
  8. for (int i = 0; i < 10; i++)

    pass 1 of 10
    31System.out.println("\nRandom booleans:");32for (int i0 = 0; i < 10; i++) {33    System.out.print(rand.nextBoolean() ? "T " : "F ");34}
    outputT 
    All 10 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
    98
    109
  9. System.out.println();

    34}35System.out.println();3637// Random longs38System.out.println("\nRandom longs:");39for (int i = 0; i < 3; i++) {
    output
    Random longs:
  10. for (int i = 0; i < 3; i++)

    pass 1 of 3
    38System.out.println("\nRandom longs:");39for (int i0 = 0; i < 3; i++) {40    System.out.println("  " + rand.nextLong());41}
    output  -5671795673574091253
    All 3 passes — pass 1 is the card above
    passi
    10
    21
    32
  11. System.out.println(" Random floats:");

    43// Random floats44System.out.println("\nRandom floats:");45for (int i = 0; i < 5; i++) {
    output
    Random floats:
  12. for (int i = 0; i < 5; i++)

    pass 1 of 5
    44System.out.println("\nRandom floats:");45for (int i0 = 0; i < 5; i++) {46    System.out.printf("  %.6f%n", rand.nextFloat());47}
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  13. System.out.println(" Gaussian (mean=0, stddev=1):");

    49// Gaussian (normal) distribution50System.out.println("\nGaussian (mean=0, stddev=1):");51for (int i = 0; i < 10; i++) {
    output
    Gaussian (mean=0, stddev=1):
  14. for (int i = 0; i < 10; i++)

    pass 1 of 10
    50System.out.println("\nGaussian (mean=0, stddev=1):");51for (int i0 = 0; i < 10; i++) {52    System.out.printf("  %.4f%n", rand.nextGaussian());53}
    All 10 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
    98
    109
  15. seeded1 ← ⟨Random B⟩, seeded2 ← ⟨Random C⟩

    55// Seeded Random (reproducible)56System.out.println("\nSeeded Random (seed=" + seed12345 + "):");57Random seeded1→ ⟨Random B⟩ = new Random(seed);58Random seeded2→ ⟨Random C⟩ = new Random(seed);5960System.out.println("First sequence:");61for (int i = 0; i < 5; i++) {
    output
    Seeded Random (seed=12345):
    First sequence:
  16. for (int i = 0; i < 5; i++)

    pass 1 of 5
    60System.out.println("First sequence:");61for (int i0 = 0; i < 5; i++) {62    System.out.println("  " + seeded1.nextInt(100));63}
    output  51
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  17. System.out.println("Second sequence (same):");

    65System.out.println("Second sequence (same):");66for (int i = 0; i < 5; i++) {
    outputSecond sequence (same):
  18. for (int i = 0; i < 5; i++)

    pass 1 of 5
    65System.out.println("Second sequence (same):");66for (int i0 = 0; i < 5; i++) {67    System.out.println("  " + seeded2.nextInt(100));68}
    output  51
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  19. separate ← ⟨Random D⟩

    70// Separate Random instance for independent sequence71System.out.println("\nSeparate seeded Random:");72Random separate→ ⟨Random D⟩ = new Random(seed + 1);73for (int i = 0; i < 5; i++) {
    output
    Separate seeded Random:
  20. for (int i = 0; i < 5; i++)

    pass 1 of 5
    72Random separate = new Random(seed + 1);73for (int i0 = 0; i < 5; i++) {74    System.out.println("  " + separate.nextInt(100));75}
    output  74
    All 5 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
  21. System.out.println(" Random.nextDouble():");

    77// Random.nextDouble() for decimal values78System.out.println("\nRandom.nextDouble():");79for (int i = 0; i < 5; i++) {
    output
    Random.nextDouble():
  22. r ← 0.5141767124330875

    pass 1 of 5
    78System.out.println("\nRandom.nextDouble():");79for (int i0 = 0; i < 5; i++) {80    double r→ 0.5141767124330875 = rand.nextDouble();  // [0.0, 1.0)81    System.out.printf("  %.6f%n", r0.5141767124330875);82}
    All 5 passes — pass 1 is the card above
    passir
    100.5141767124330875
    210.5173344627422577
    320.0054778097797331116
    430.11451624896785961
    540.1514197810837441
  23. System.out.println(" Random.nextDouble() in range [10, 20):");

    84// Custom range using Random.nextDouble()85System.out.println("\nRandom.nextDouble() in range [10, 20):");86for (int i = 0; i < 5; i++) {
    output
    Random.nextDouble() in range [10, 20):
  24. min ← 10, max ← 20, r ← 11

    pass 1 of 5
    85System.out.println("\nRandom.nextDouble() in range [10, 20):");86for (int i0 = 0; i < 5; i++) {87    int min→ 10 = 10;88    int max→ 20 = 20;89    int r→ 11 = (int)(rand.nextDouble() * (max20 - min10)) + min;90    System.out.println("  " + r11);91}
    output  11
    All 5 passes — pass 1 is the card above
    passiminmaxr
    10102011
    21102018
    32102014
    43102013
    54102019
  25. byte[] bytes = new byte[10];

    93// nextBytes94System.out.println("\nRandom bytes:");95byte[] bytes = new byte[10];96rand.nextBytes(bytes);97for (byte b : bytes) {
    output
    Random bytes:
  26. for (byte b : bytes)

    pass 1 of 10
    96rand.nextBytes(bytes);97for (byte b-120 : bytes) {98    System.out.printf("%3d ", b-120);99}
    All 10 passes — pass 1 is the card above
    passb
    1-120
    298
    386
    430
    580
    6125
    768
    8-10
    940
    1024
  27. System.out.println();

    99    }100    System.out.println();101}
Seed An initial value that determines the entire sequence of random numbers. Same seed produces same sequence, useful for testing.

Random Ranges

Generate numbers within specific ranges.

Ranges.java
Replay: real traced execution (multi-file project)
// Random ranges

import java.util.Random;

public class Ranges {
    public static void main(String[] args) {
        int seed = 42;
        Random rand = new Random(seed);
        System.out.println("Seed: " + seed);

        // Range [min, max]
        System.out.println("Range [10, 20]:");
        int betweenTenAndTwenty = randInt(rand, 10, 20);
        System.out.println(betweenTenAndTwenty);

        // Range [0, max]
        System.out.println("\nRange [0, 50]:");
        int upToFifty = randInt(rand, 0, 50);
        System.out.println(upToFifty);

        // Negative range [-10, 10]
        System.out.println("\nRange [-10, 10]:");
        int centered = randInt(rand, -10, 10);
        System.out.println(centered);

        // Double range [0.0, 10.0]
        System.out.println("\nDouble range [0.0, 10.0]:");
        double decimal = randDouble(rand, 0.0, 10.0);
        System.out.printf("%.2f%n", decimal);

        // Double range [-1.0, 1.0]
        System.out.println("\nDouble range [-1.0, 1.0]:");
        double normalized = randDouble(rand, -1.0, 1.0);
        System.out.printf("%.2f%n", normalized);

        // Dice roll (1-6)
        System.out.println("\nDice rolls:");
        int roll1 = randInt(rand, 1, 6);
        int roll2 = randInt(rand, 1, 6);
        System.out.println("Two rolls: " + roll1 + ", " + roll2);

        // Coin flip
        System.out.println("\nCoin flips:");
        boolean heads = rand.nextBoolean();
        System.out.println(heads ? "Heads" : "Tails");

        // Percentage/probability
        System.out.println("\n20% chance events:");
        boolean success = rand.nextDouble() < 0.20;
        System.out.println("Success: " + success);
    }
    public static int randInt(Random rand, int min, int max) {
        return rand.nextInt(max - min + 1) + min;
    }
    public static double randDouble(Random rand, double min, double max) {
        return min + (max - min) * rand.nextDouble();
    }

    //help h1
    // rand.nextInt(max - min + 1) + min - [min, max]
    // rand.nextInt(max - min) + min - [min, max)
    // min + (max - min) * rand.nextDouble() - double [min, max)
    // rand.nextDouble() < prob - probability check
    // rand.nextBoolean() - 50% chance
    // Use helpers for cleaner code
    //end
}
  1. seed ← 42, rand ← ⟨Random A⟩

    5public class Ranges {6    public static void main(String[] args) {7        int seed→ 42 = 42;8        Random rand→ ⟨Random A⟩ = new Random(seed);9        System.out.println("Seed: " + seed42);10        11        // Range [min, max]12        System.out.println("Range [10, 20]:");13        int betweenTenAndTwenty = randInt(rand⟨Random A⟩, 10, 20);14        System.out.println(betweenTenAndTwenty);
    outputSeed: 42
    Range [10, 20]:
  2. public static int randInt(Random rand, int min, int max)

    pass 1 of 5
    51}52public static int randInt(Random rand⟨Random A⟩, int min10, int max20) {53    return rand.nextInt(max20 - min10 + 1) + min;54}
    All 5 passes — pass 1 is the card above
    passminmax
    11020
    2050
    3-1010
    416
    516
  3. betweenTenAndTwenty ← 17

    12System.out.println("Range [10, 20]:");13int betweenTenAndTwenty→ 17 = randInt(rand⟨Random A⟩, 10, 20);14System.out.println(betweenTenAndTwenty17);1516// Range [0, max]17System.out.println("\nRange [0, 50]:");18int upToFifty = randInt(rand⟨Random A⟩, 0, 50);19System.out.println(upToFifty);
    output17
    
    Range [0, 50]:
  4. upToFifty ← 45

    17System.out.println("\nRange [0, 50]:");18int upToFifty→ 45 = randInt(rand⟨Random A⟩, 0, 50);19System.out.println(upToFifty45);2021// Negative range [-10, 10]22System.out.println("\nRange [-10, 10]:");23int centered = randInt(rand⟨Random A⟩, -10, 10);24System.out.println(centered);
    output45
    
    Range [-10, 10]:
  5. centered ← -4

    22System.out.println("\nRange [-10, 10]:");23int centered→ -4 = randInt(rand⟨Random A⟩, -10, 10);24System.out.println(centered-4);2526// Double range [0.0, 10.0]27System.out.println("\nDouble range [0.0, 10.0]:");28double decimal = randDouble(rand⟨Random A⟩, 0.0, 10.0);29System.out.printf("%.2f%n", decimal);
    output-4
    
    Double range [0.0, 10.0]:
  6. public static double randDouble(Random rand, double min, double max)

    pass 1 of 2
    54}55public static double randDouble(Random rand⟨Random A⟩, double min0.0, double max10.0) {56    return min0.0 + (max10.0 - min) * rand.nextDouble();57}
  7. decimal ← 0.47939305137387644

    27System.out.println("\nDouble range [0.0, 10.0]:");28double decimal→ 0.47939305137387644 = randDouble(rand⟨Random A⟩, 0.0, 10.0);29System.out.printf("%.2f%n", decimal0.47939305137387644);3031// Double range [-1.0, 1.0]32System.out.println("\nDouble range [-1.0, 1.0]:");33double normalized = randDouble(rand⟨Random A⟩, -1.0, 1.0);34System.out.printf("%.2f%n", normalized);
    output
    Double range [-1.0, 1.0]:
  8. public static double randDouble(Random rand, double min, double max)

    pass 2 of 2
    54}55public static double randDouble(Random rand⟨Random A⟩, double min-1.0, double max1.0) {56    return min-1.0 + (max1.0 - min) * rand.nextDouble();57}
  9. normalized ← 0.8841470860564256

    32System.out.println("\nDouble range [-1.0, 1.0]:");33double normalized→ 0.8841470860564256 = randDouble(rand⟨Random A⟩, -1.0, 1.0);34System.out.printf("%.2f%n", normalized0.8841470860564256);3536// Dice roll (1-6)37System.out.println("\nDice rolls:");38int roll1 = randInt(rand⟨Random A⟩, 1, 6);39int roll2 = randInt(rand, 1, 6);
    output
    Dice rolls:
  10. roll1 ← 3

    37System.out.println("\nDice rolls:");38int roll1→ 3 = randInt(rand⟨Random A⟩, 1, 6);39int roll2 = randInt(rand⟨Random A⟩, 1, 6);40System.out.println("Two rolls: " + roll1 + ", " + roll2);
  11. roll2 ← 2, heads ← false, success ← false

    38    int roll1 = randInt(rand, 1, 6);39    int roll2→ 2 = randInt(rand⟨Random A⟩, 1, 6);40    System.out.println("Two rolls: " + roll13 + ", " + roll22);41    42    // Coin flip43    System.out.println("\nCoin flips:");44    boolean heads→ false = rand.nextBoolean();45    System.out.println(headsfalse ? "Heads" : "Tails");46    47    // Percentage/probability48    System.out.println("\n20% chance events:");49    boolean success→ false = rand.nextDouble() < 0.20;50    System.out.println("Success: " + successfalse);51}
    outputTwo rolls: 3, 2
    
    Coin flips:
    Tails
    
    20% chance events:
    Success: false

Random Distributions

Generate numbers following different statistical distributions.

Distributions.java
Replay: real traced execution (multi-file project)
// Distributions

import java.util.Random;

public class Distributions {
    public static void main(String[] args) {
        int seed = 42;
        int samples = 8;
        Random rand = new Random(seed);
        System.out.println("Seed: " + seed);

        // Uniform distribution [0, 100)
        System.out.println("Uniform distribution [0, 100):");
        int[] uniform = new int[5];
        for (int i = 0; i < samples; i++) {
            int bin = rand.nextInt(100) / 20;
            uniform[bin]++;
        }
        printHistogram("Uniform", uniform, samples);

        // Gaussian (normal) distribution
        System.out.println("\nGaussian distribution (mean=50, stddev=10):");
        int[] gaussian = new int[5];
        for (int i = 0; i < samples; i++) {
            double value = rand.nextGaussian() * 10 + 50;
            int bin = Math.max(0, Math.min(4, (int)(value / 20)));
            gaussian[bin]++;
        }
        printHistogram("Gaussian", gaussian, samples);

        // Exponential distribution
        System.out.println("\nExponential distribution (lambda=0.1):");
        int[] exponential = new int[5];
        for (int i = 0; i < samples; i++) {
            double value = exponentialRandom(rand, 0.1);
            int bin = Math.min(4, (int)(value / 20));
            exponential[bin]++;
        }
        printHistogram("Exponential", exponential, samples);

        // Binomial distribution (coin flips)
        System.out.println("\nBinomial distribution (10 flips, p=0.5):");
        int[] binomial = new int[11];
        for (int i = 0; i < samples; i++) {
            int heads = 0;
            for (int j = 0; j < 10; j++) {
                if (rand.nextBoolean()) heads++;
            }
            binomial[heads]++;
        }
        System.out.println("Number of heads:");
        for (int i = 0; i <= 10; i++) {
            System.out.printf("%2d: %d (%.1f%%)%n", i, binomial[i], binomial[i] * 100.0 / samples);
        }

        // Poisson-like distribution
        System.out.println("\nPoisson-like distribution:");
        int[] poisson = new int[15];
        for (int i = 0; i < samples; i++) {
            int events = poissonRandom(rand, 5.0);
            if (events < poisson.length) {
                poisson[events]++;
            }
        }
        System.out.println("Number of events:");
        for (int i = 0; i < Math.min(12, poisson.length); i++) {
            System.out.printf("%2d: %d (%.1f%%)%n", i, poisson[i], poisson[i] * 100.0 / samples);
        }

        // Triangle distribution
        System.out.println("\nTriangle distribution [0, 100]:");
        int[] triangle = new int[5];
        for (int i = 0; i < samples; i++) {
            double value = triangleRandom(rand, 0, 100, 50);
            int bin = Math.min(4, (int)(value / 20));
            triangle[bin]++;
        }
        printHistogram("Triangle", triangle, samples);
    }
    public static double exponentialRandom(Random rand, double lambda) {
        return -Math.log(1 - rand.nextDouble()) / lambda;
    }
    public static int poissonRandom(Random rand, double lambda) {
        double L = Math.exp(-lambda);
        int k = 0;
        double p = 1.0;

        do {
            k++;
            p *= rand.nextDouble();
        } while (p > L);

        return k - 1;
    }
    public static double triangleRandom(Random rand, double min, double max, double mode) {
        double u = rand.nextDouble();
        double c = (mode - min) / (max - min);

        if (u < c) {
            return min + Math.sqrt(u * (max - min) * (mode - min));
        } else {
            return max - Math.sqrt((1 - u) * (max - min) * (max - mode));
        }
    }
    public static void printHistogram(String name, int[] bins, int total) {
        for (int i = 0; i < bins.length; i++) {
            int percent = (bins[i] * 100) / total;
            String bar = "█".repeat(percent);
            System.out.printf("[%d-%d): %4d (%.1f%%) %s%n",
                i * 20, (i + 1) * 20, bins[i], bins[i] * 100.0 / total, bar);
        }
    }

    //help h1
    // Uniform: rand.nextInt(n) or nextDouble()
    // Gaussian: rand.nextGaussian() (mean=0, stddev=1)
    //   Scale: value * stddev + mean
    // Exponential: -log(1-U) / lambda
    // Poisson: inverse transform method
    // Triangle: inverse CDF
    // Histogram to visualize distribution
    //end
}
  1. seed ← 42, samples ← 8, rand ← ⟨Random A⟩

    5public class Distributions {6    public static void main(String[] args) {7        int seed→ 42 = 42;8        int samples→ 8 = 8;9        Random rand→ ⟨Random A⟩ = new Random(seed);10        System.out.println("Seed: " + seed42);11        12        // Uniform distribution [0, 100)13        System.out.println("Uniform distribution [0, 100):");14        int[] uniform = new int[5];15        for (int i = 0; i < samples; i++) {
    outputSeed: 42
    Uniform distribution [0, 100):
  2. bin ← 1, uniform[bin] ← 1

    pass 1 of 8
    14int[] uniform = new int[5];15for (int i0 = 0; i < samples8; i++) {16    int bin→ 1 = rand.nextInt(100) / 20;17    uniform[bin]→ 1++;18}
    All 8 passes — pass 1 is the card above
    passibinuniform[bin]
    1010 1
    2130 1
    3220 1
    4340 1
    5431 2
    6511 2
    7600 1
    8701 2
  3. printHistogram("Uniform", uniform, samples);

    18}19printHistogram("Uniform", uniform, samples8);
  4. public static void printHistogram(String name, int[] bins, int total)

    pass 1 of 4
    104}105public static void printHistogram(String nameUniform, int[] bins, int total8) {106    for (int i = 0; i < bins.length; i++) {
    All 4 passes — pass 1 is the card above
    passname
    1Uniform
    2Gaussian
    3Exponential
    4Triangle
  5. percent ← 25, bar ← █████████████████████████

    pass 1 of 20
    105public static void printHistogram(String name, int[] bins, int total) {106    for (int i0 = 0; i < bins.length5; i++) {107        int percent→ 25 = (bins[i]2 * 100) / total8;108        String bar→ █████████████████████████ = "█".repeat(percent25);109        System.out.printf("[%d-%d): %4d (%.1f%%) %s%n",110            i0 * 20, (i + 1) * 20, bins[i]2, bins[i] * 100.0 / total8, bar█████████████████████████);111    }
    20 passes — pass 1 is the card above
    passibins[i]samplespercentbar
    10225█████████████████████████
    21225█████████████████████████
    32112████████████
    43225█████████████████████████
    541812████████████
    6000(empty)
    71112████████████
    82675███████████████████████████████████████████████████████████████████████████
    93112████████████
    ⋯ 9 more passes ⋯
    193337█████████████████████████████████████
    204080(empty)
  6. value ← 52.8097763807278, bin ← 2, gaussian[bin] ← 1

    pass 1 of 8
    23int[] gaussian = new int[5];24for (int i0 = 0; i < samples8; i++) {25    double value→ 52.8097763807278 = rand.nextGaussian() * 10 + 50;26    int bin→ 2 = Math.max(0, Math.min(4, (int)(value52.8097763807278 / 20)));27    gaussian[bin]→ 1++;28}
    All 8 passes — pass 1 is the card above
    passivaluebingaussian[bin]
    1052.809776380727820 1
    2156.8462279563265521 2
    3241.8277859260127322 3
    4336.0335659732195710 1
    5448.09055486929124623 4
    6564.862133923906530 1
    7658.0230714968736324 5
    8748.7848707533450725 6
  7. printHistogram("Gaussian", gaussian, samples);

    28}29printHistogram("Gaussian", gaussian, samples8);
  8. for (int i = 0; i < samples; i++)

    pass 1 of 8
    33int[] exponential = new int[5];34for (int i0 = 0; i < samples8; i++) {35    double value = exponentialRandom(rand⟨Random A⟩, 0.1);36    int bin = Math.min(4, (int)(value / 20));
    All 8 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
  9. public static double exponentialRandom(Random rand, double lambda)

    pass 1 of 8
    79}80public static double exponentialRandom(Random rand⟨Random A⟩, double lambda0.1) {81    return -Math.log(1 - rand.nextDouble()) / lambda0.1;82}
  10. value ← 13.859191565397232, bin ← 0, exponential[bin] ← 1

    34for (int i = 0; i < samples; i++) {35    double value→ 13.859191565397232 = exponentialRandom(rand⟨Random A⟩, 0.1);36    int bin→ 0 = Math.min(4, (int)(value13.859191565397232 / 20));37    exponential[bin]→ 1++;38}
  11. value ← 4.886840254333257, bin ← 0, exponential[bin] ← 2

    34for (int i = 0; i < samples; i++) {35    double value→ 4.886840254333257 = exponentialRandom(rand⟨Random A⟩, 0.1);36    int bin→ 0 = Math.min(4, (int)(value4.886840254333257 / 20));37    exponential[bin]→ 2++;38}
  12. value ← 1.952590600335157, bin ← 0, exponential[bin] ← 3

    34for (int i = 0; i < samples; i++) {35    double value→ 1.952590600335157 = exponentialRandom(rand⟨Random A⟩, 0.1);36    int bin→ 0 = Math.min(4, (int)(value1.952590600335157 / 20));37    exponential[bin]→ 3++;38}
  13. value ← 9.022643404681773, bin ← 0, exponential[bin] ← 4

    34for (int i = 0; i < samples; i++) {35    double value→ 9.022643404681773 = exponentialRandom(rand⟨Random A⟩, 0.1);36    int bin→ 0 = Math.min(4, (int)(value9.022643404681773 / 20));37    exponential[bin]→ 4++;38}
  14. value ← 2.3542816016939736, bin ← 0, exponential[bin] ← 5

    34for (int i = 0; i < samples; i++) {35    double value→ 2.3542816016939736 = exponentialRandom(rand⟨Random A⟩, 0.1);36    int bin→ 0 = Math.min(4, (int)(value2.3542816016939736 / 20));37    exponential[bin]→ 5++;38}
  15. value ← 17.485038604245222, bin ← 0, exponential[bin] ← 6

    34for (int i = 0; i < samples; i++) {35    double value→ 17.485038604245222 = exponentialRandom(rand⟨Random A⟩, 0.1);36    int bin→ 0 = Math.min(4, (int)(value17.485038604245222 / 20));37    exponential[bin]→ 6++;38}
  16. value ← 1.8900536901058558, bin ← 0, exponential[bin] ← 7

    34for (int i = 0; i < samples; i++) {35    double value→ 1.8900536901058558 = exponentialRandom(rand⟨Random A⟩, 0.1);36    int bin→ 0 = Math.min(4, (int)(value1.8900536901058558 / 20));37    exponential[bin]→ 7++;38}
  17. value ← 8.853430445469202, bin ← 0, exponential[bin] ← 8

    34for (int i = 0; i < samples; i++) {35    double value→ 8.853430445469202 = exponentialRandom(rand⟨Random A⟩, 0.1);36    int bin→ 0 = Math.min(4, (int)(value8.853430445469202 / 20));37    exponential[bin]→ 8++;38}39printHistogram("Exponential", exponential, samples8);
  18. heads ← 0

    pass 1 of 8
    43int[] binomial = new int[11];44for (int i0 = 0; i < samples8; i++) {45    int heads→ 0 = 0;46    for (int j = 0; j < 10; j++) {
    All 8 passes — pass 1 is the card above
    passiheads
    100
    210
    320
    430
    540
    650
    760
    870
  19. for (int j = 0; j < 10; j++)

    pass 1 of 80
    45int heads = 0;46for (int j0 = 0; j < 10; j++) {47    if (rand.nextBoolean()) heads++;
    80 passes — pass 1 is the card above
    passj
    10
    21
    32
    43
    54
    65
    76
    87
    98
    ⋯ 69 more passes ⋯
    798
    809
  20. heads ← 1

    pass 1 of 36
    46for (int j = 0; j < 10; j++) {47    if (rand.nextBoolean()) heads→ 1++;48}
    36 passes — pass 1 is the card above
    passheads
    10 1
    21 2
    32 3
    43 4
    54 5
    65 6
    70 1
    81 2
    92 3
    ⋯ 25 more passes ⋯
    351 2
    362 3
  21. binomial[heads] ← 1

    48    }49    binomial[heads]→ 1++;50}
    values this step6heads
  22. binomial[heads] ← 1

    48    }49    binomial[heads]→ 1++;50}
    values this step5heads
  23. binomial[heads] ← 2

    48    }49    binomial[heads]→ 2++;50}
    values this step5heads
  24. binomial[heads] ← 1

    48    }49    binomial[heads]→ 1++;50}
    values this step3heads
  25. binomial[heads] ← 3

    48    }49    binomial[heads]→ 3++;50}
    values this step5heads
  26. binomial[heads] ← 1

    48    }49    binomial[heads]→ 1++;50}
    values this step4heads
  27. binomial[heads] ← 4

    48    }49    binomial[heads]→ 4++;50}
    values this step5heads
  28. binomial[heads] ← 2

    48    }49    binomial[heads]→ 2++;50}
    values this step3heads
  29. System.out.println("Number of heads:");

    50}51System.out.println("Number of heads:");52for (int i = 0; i <= 10; i++) {
    outputNumber of heads:
  30. for (int i = 0; i <= 10; i++)

    pass 1 of 11
    51System.out.println("Number of heads:");52for (int i0 = 0; i <= 10; i++) {53    System.out.printf("%2d: %d (%.1f%%)%n", i0, binomial[i]0, binomial[i] * 100.0 / samples8);54}
    All 11 passes — pass 1 is the card above
    passibinomial[i]
    100
    210
    320
    432
    541
    654
    761
    870
    980
    1090
    11100
  31. int[] poisson = new int[15];

    56// Poisson-like distribution57System.out.println("\nPoisson-like distribution:");58int[] poisson = new int[15];59for (int i = 0; i < samples; i++) {
    output
    Poisson-like distribution:
  32. for (int i = 0; i < samples; i++)

    pass 1 of 8
    58int[] poisson = new int[15];59for (int i0 = 0; i < samples8; i++) {60    int events = poissonRandom(rand⟨Random A⟩, 5.0);61    if (events < poisson.length) {
    All 8 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
  33. L ← 0.006737946999085467, k ← 0, p ← 1.0

    pass 1 of 8
    82}83public static int poissonRandom(Random rand⟨Random A⟩, double lambda5.0) {84    double L→ 0.006737946999085467 = Math.exp(-lambda5.0);85    int k→ 0 = 0;86    double p→ 1.0 = 1.0;
    All 8 passes — pass 1 is the card above
    passLkp
    10.00673794699908546701.0
    20.00673794699908546701.0
    30.00673794699908546701.0
    40.00673794699908546701.0
    50.00673794699908546701.0
    60.00673794699908546701.0
    70.00673794699908546701.0
    80.00673794699908546701.0
  34. k ← 1, p ← 0.6972487292697295

    pass 1 of 45
    88do {89    k→ 1++;90    p→ 0.6972487292697295 *= rand.nextDouble();91} while (p > L);
    45 passes — pass 1 is the card above
    passkp
    10 11.0 0.6972487292697295
    21 20.6972487292697295 0.6335303614456775
    32 30.6335303614456775 0.1242651253458207
    43 40.1242651253458207 0.10054599677108673
    54 50.10054599677108673 0.06313617708218094
    65 60.06313617708218094 0.02925725843539916
    76 70.02925725843539916 0.008940408329833621
    87 80.008940408329833621 0.004827010803408223
    90 11.0 0.6351110144563881
    ⋯ 34 more passes ⋯
    444 50.13541228243409476 0.046573991075327725
    455 60.046573991075327725 6.546355631740219E-4
  35. return k - 1;

    93    return k8 - 1;94}
  36. events ← 7

    59for (int i = 0; i < samples; i++) {60    int events→ 7 = poissonRandom(rand⟨Random A⟩, 5.0);61    if (events < poisson.length) {
  37. poisson[events] ← 1

    pass 1 of 8
    60int events = poissonRandom(rand, 5.0);61if (events7 < poisson.length15) {62    poisson[events]→ 1++;63}
    All 8 passes — pass 1 is the card above
    passeventspoisson[events]
    170 1
    230 1
    331 2
    480 1
    550 1
    632 3
    733 4
    851 2
  38. return k - 1;

    93    return k4 - 1;94}
  39. events ← 3

    59for (int i = 0; i < samples; i++) {60    int events→ 3 = poissonRandom(rand⟨Random A⟩, 5.0);61    if (events < poisson.length) {
  40. return k - 1;

    93    return k4 - 1;94}
  41. events ← 3

    59for (int i = 0; i < samples; i++) {60    int events→ 3 = poissonRandom(rand⟨Random A⟩, 5.0);61    if (events < poisson.length) {
  42. return k - 1;

    93    return k9 - 1;94}
  43. events ← 8

    59for (int i = 0; i < samples; i++) {60    int events→ 8 = poissonRandom(rand⟨Random A⟩, 5.0);61    if (events < poisson.length) {
  44. return k - 1;

    93    return k6 - 1;94}
  45. events ← 5

    59for (int i = 0; i < samples; i++) {60    int events→ 5 = poissonRandom(rand⟨Random A⟩, 5.0);61    if (events < poisson.length) {
  46. return k - 1;

    93    return k4 - 1;94}
  47. events ← 3

    59for (int i = 0; i < samples; i++) {60    int events→ 3 = poissonRandom(rand⟨Random A⟩, 5.0);61    if (events < poisson.length) {
  48. return k - 1;

    93    return k4 - 1;94}
  49. events ← 3

    59for (int i = 0; i < samples; i++) {60    int events→ 3 = poissonRandom(rand⟨Random A⟩, 5.0);61    if (events < poisson.length) {
  50. return k - 1;

    93    return k6 - 1;94}
  51. events ← 5

    59for (int i = 0; i < samples; i++) {60    int events→ 5 = poissonRandom(rand⟨Random A⟩, 5.0);61    if (events < poisson.length) {
  52. System.out.println("Number of events:");

    64}65System.out.println("Number of events:");66for (int i = 0; i < Math.min(12, poisson.length); i++) {
    outputNumber of events:
  53. for (int i = 0; i < Math.min(12, poisson.length); i++)

    pass 1 of 12
    65System.out.println("Number of events:");66for (int i0 = 0; i < Math.min(12, poisson.length15); i++) {67    System.out.printf("%2d: %d (%.1f%%)%n", i0, poisson[i]0, poisson[i] * 100.0 / samples8);68}
    All 12 passes — pass 1 is the card above
    passipoisson[i]
    100
    210
    320
    434
    540
    652
    760
    871
    981
    1090
    11100
    12110
  54. int[] triangle = new int[5];

    70// Triangle distribution71System.out.println("\nTriangle distribution [0, 100]:");72int[] triangle = new int[5];73for (int i = 0; i < samples; i++) {
    output
    Triangle distribution [0, 100]:
  55. for (int i = 0; i < samples; i++)

    pass 1 of 8
    72int[] triangle = new int[5];73for (int i0 = 0; i < samples8; i++) {74    double value = triangleRandom(rand⟨Random A⟩, 0, 100, 50);75    int bin = Math.min(4, (int)(value / 20));
    All 8 passes — pass 1 is the card above
    passiucminmaxmode
    10
    21
    32
    43
    54
    65
    760.11575012371962590.50.0100.050.0
    87
  56. u ← 0.8095941248100625, c ← 0.5

    pass 1 of 8
    94}95public static double triangleRandom(Random rand⟨Random A⟩, double min0.0, double max100.0, double mode50.0) {96    double u→ 0.8095941248100625 = rand.nextDouble();97    double c→ 0.5 = (mode50.0 - min0.0) / (max100.0 - min);
    All 8 passes — pass 1 is the card above
    passuc
    10.80959412481006250.5
    20.52149430368975580.5
    30.8351555550077010.5
    40.58346164859111890.5
    50.68824606934751490.5
    60.55638220131905190.5
    70.11575012371962590.5
    80.58850863689428990.5
  57. else

    pass 1 of 7
    100    return min + Math.sqrt(u * (max - min) * (mode - min));101} else {102    return max100.0 - Math.sqrt((1 - u0.8095941248100625) * (max - min0.0) * (max - mode50.0));103}
    All 7 passes — pass 1 is the card above
    passu
    10.8095941248100625
    20.5214943036897558
    30.835155555007701
    40.5834616485911189
    50.6882460693475149
    60.5563822013190519
    70.5885086368942899
  58. value ← 69.14502672258996, bin ← 3, triangle[bin] ← 1

    73for (int i = 0; i < samples; i++) {74    double value→ 69.14502672258996 = triangleRandom(rand⟨Random A⟩, 0, 100, 50);75    int bin→ 3 = Math.min(4, (int)(value69.14502672258996 / 20));76    triangle[bin]→ 1++;77}
  59. value ← 51.086520451400915, bin ← 2, triangle[bin] ← 1

    73for (int i = 0; i < samples; i++) {74    double value→ 51.086520451400915 = triangleRandom(rand⟨Random A⟩, 0, 100, 50);75    int bin→ 2 = Math.min(4, (int)(value51.086520451400915 / 20));76    triangle[bin]→ 1++;77}
  60. value ← 71.29072928544693, bin ← 3, triangle[bin] ← 2

    73for (int i = 0; i < samples; i++) {74    double value→ 71.29072928544693 = triangleRandom(rand⟨Random A⟩, 0, 100, 50);75    int bin→ 3 = Math.min(4, (int)(value71.29072928544693 / 20));76    triangle[bin]→ 2++;77}
  61. value ← 54.36348219852434, bin ← 2, triangle[bin] ← 2

    73for (int i = 0; i < samples; i++) {74    double value→ 54.36348219852434 = triangleRandom(rand⟨Random A⟩, 0, 100, 50);75    int bin→ 2 = Math.min(4, (int)(value54.36348219852434 / 20));76    triangle[bin]→ 2++;77}
  62. value ← 60.51874301314071, bin ← 3, triangle[bin] ← 3

    73for (int i = 0; i < samples; i++) {74    double value→ 60.51874301314071 = triangleRandom(rand⟨Random A⟩, 0, 100, 50);75    int bin→ 3 = Math.min(4, (int)(value60.51874301314071 / 20));76    triangle[bin]→ 3++;77}
  63. value ← 52.903407836609446, bin ← 2, triangle[bin] ← 3

    73for (int i = 0; i < samples; i++) {74    double value→ 52.903407836609446 = triangleRandom(rand⟨Random A⟩, 0, 100, 50);75    int bin→ 2 = Math.min(4, (int)(value52.903407836609446 / 20));76    triangle[bin]→ 3++;77}
  64. if (u < c)

    99if (u0.1157501237196259 < c0.5) {100    return min0.0 + Math.sqrt(u0.1157501237196259 * (max100.0 - min) * (mode50.0 - min));101} else {
  65. value ← 24.057236304241794, bin ← 1, triangle[bin] ← 1

    73for (int i = 0; i < samples; i++) {74    double value→ 24.057236304241794 = triangleRandom(rand⟨Random A⟩, 0, 100, 50);75    int bin→ 1 = Math.min(4, (int)(value24.057236304241794 / 20));76    triangle[bin]→ 1++;77}
  66. value ← 54.6408023050611, bin ← 2, triangle[bin] ← 4

    73    for (int i = 0; i < samples; i++) {74        double value→ 54.6408023050611 = triangleRandom(rand⟨Random A⟩, 0, 100, 50);75        int bin→ 2 = Math.min(4, (int)(value54.6408023050611 / 20));76        triangle[bin]→ 4++;77    }78    printHistogram("Triangle", triangle, samples8);79}
Gaussian distribution A bell curve distribution where most values cluster near the mean, useful for realistic simulations.

Random Strings

Generate random strings for IDs, passwords, or test data.

Strings.java
Replay: real traced execution (multi-file project)
// Random strings and data

import java.util.Random;

public class Strings {
    public static void main(String[] args) {
        int seed = 42;
        Random rand = new Random(seed);
        System.out.println("Seed: " + seed);

        // Random letters
        System.out.println("Random letters:");
        for (int i = 0; i < 4; i++) {
            char c = randomLetter(rand);
            System.out.print(c + " ");
        }
        System.out.println();

        // Random uppercase letters
        System.out.println("\nRandom uppercase:");
        for (int i = 0; i < 4; i++) {
            char c = randomUppercase(rand);
            System.out.print(c + " ");
        }
        System.out.println();

        // Random digit
        System.out.println("\nRandom digits:");
        for (int i = 0; i < 4; i++) {
            char c = randomDigit(rand);
            System.out.print(c + " ");
        }
        System.out.println();

        // Random string
        System.out.println("\nRandom strings:");
        for (int i = 0; i < 2; i++) {
            String s = randomString(rand, 5);
            System.out.println("  " + s);
        }

        // Random alphanumeric
        System.out.println("\nRandom alphanumeric:");
        for (int i = 0; i < 2; i++) {
            String s = randomAlphanumeric(rand, 6);
            System.out.println("  " + s);
        }

        // Random password
        System.out.println("\nRandom passwords:");
        for (int i = 0; i < 2; i++) {
            String pwd = randomPassword(rand, 8);
            System.out.println("  " + pwd);
        }

        // Random hex string
        System.out.println("\nRandom hex strings:");
        for (int i = 0; i < 2; i++) {
            String hex = randomHex(rand, 8);
            System.out.println("  " + hex);
        }

        // Random UUID-like
        System.out.println("\nRandom UUID-like:");
        for (int i = 0; i < 1; i++) {
            String uuid = randomUUID(rand);
            System.out.println("  " + uuid);
        }

        // Random email
        System.out.println("\nRandom emails:");
        for (int i = 0; i < 2; i++) {
            String email = randomEmail(rand);
            System.out.println("  " + email);
        }

        // Random phone number
        System.out.println("\nRandom phone numbers:");
        for (int i = 0; i < 2; i++) {
            String phone = randomPhone(rand);
            System.out.println("  " + phone);
        }
    }
    public static char randomLetter(Random rand) {
        return (char)('a' + rand.nextInt(26));
    }
    public static char randomUppercase(Random rand) {
        return (char)('A' + rand.nextInt(26));
    }
    public static char randomDigit(Random rand) {
        return (char)('0' + rand.nextInt(10));
    }
    public static String randomString(Random rand, int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(randomLetter(rand));
        }
        return sb.toString();
    }
    public static String randomAlphanumeric(Random rand, int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(rand.nextInt(chars.length())));
        }
        return sb.toString();
    }
    public static String randomPassword(Random rand, int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(rand.nextInt(chars.length())));
        }
        return sb.toString();
    }
    public static String randomHex(Random rand, int length) {
        String hex = "0123456789abcdef";
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(hex.charAt(rand.nextInt(16)));
        }
        return sb.toString();
    }
    public static String randomUUID(Random rand) {
        return String.format("%s-%s-%s-%s-%s",
            randomHex(rand, 8),
            randomHex(rand, 4),
            randomHex(rand, 4),
            randomHex(rand, 4),
            randomHex(rand, 12)
        );
    }
    public static String randomEmail(Random rand) {
        String username = randomString(rand, 8);
        String[] domains = {"gmail.com", "yahoo.com", "hotmail.com", "example.com"};
        String domain = domains[rand.nextInt(domains.length)];
        return username + "@" + domain;
    }
    public static String randomPhone(Random rand) {
        int area = 200 + rand.nextInt(800);
        int exchange = 200 + rand.nextInt(800);
        int number = rand.nextInt(10000);
        return String.format("(%03d) %03d-%04d", area, exchange, number);
    }

    //help h1
    // (char)('a' + rand.nextInt(26)) - random letter
    // chars.charAt(rand.nextInt(chars.length())) - from string
    // StringBuilder for building strings
    // randomAlphanumeric for IDs, tokens
    // randomPassword for secure strings
    // randomHex for hexadecimal strings
    // Combine helpers for complex formats
    //end
}
  1. seed ← 42, rand ← ⟨Random A⟩

    5public class Strings {6    public static void main(String[] args) {7        int seed→ 42 = 42;8        Random rand→ ⟨Random A⟩ = new Random(seed);9        System.out.println("Seed: " + seed42);10        11        // Random letters12        System.out.println("Random letters:");13        for (int i = 0; i < 4; i++) {
    outputSeed: 42
    Random letters:
  2. for (int i = 0; i < 4; i++)

    pass 1 of 4
    12System.out.println("Random letters:");13for (int i0 = 0; i < 4; i++) {14    char c = randomLetter(rand⟨Random A⟩);15    System.out.print(c + " ");
    All 4 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
  3. public static char randomLetter(Random rand)

    pass 1 of 30
    83}84public static char randomLetter(Random rand⟨Random A⟩) {85    return (char)('a' + rand.nextInt(26));86}
  4. c ← a

    13for (int i = 0; i < 4; i++) {14    char c→ a = randomLetter(rand⟨Random A⟩);15    System.out.print(ca + " ");16}
    outputa 
  5. c ← h

    13for (int i = 0; i < 4; i++) {14    char c→ h = randomLetter(rand⟨Random A⟩);15    System.out.print(ch + " ");16}
    outputh 
  6. c ← w

    13for (int i = 0; i < 4; i++) {14    char c→ w = randomLetter(rand⟨Random A⟩);15    System.out.print(cw + " ");16}
    outputw 
  7. c ← m

    13for (int i = 0; i < 4; i++) {14    char c→ m = randomLetter(rand⟨Random A⟩);15    System.out.print(cm + " ");16}17System.out.println();1819// Random uppercase letters20System.out.println("\nRandom uppercase:");21for (int i = 0; i < 4; i++) {
    outputm
    
    Random uppercase:
  8. for (int i = 0; i < 4; i++)

    pass 1 of 4
    20System.out.println("\nRandom uppercase:");21for (int i0 = 0; i < 4; i++) {22    char c = randomUppercase(rand⟨Random A⟩);23    System.out.print(c + " ");
    All 4 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
  9. public static char randomUppercase(Random rand)

    pass 1 of 4
    86}87public static char randomUppercase(Random rand⟨Random A⟩) {88    return (char)('A' + rand.nextInt(26));89}
  10. c ← A

    21for (int i = 0; i < 4; i++) {22    char c→ A = randomUppercase(rand⟨Random A⟩);23    System.out.print(cA + " ");24}
    outputA 
  11. c ← R

    21for (int i = 0; i < 4; i++) {22    char c→ R = randomUppercase(rand⟨Random A⟩);23    System.out.print(cR + " ");24}
    outputR 
  12. c ← N

    21for (int i = 0; i < 4; i++) {22    char c→ N = randomUppercase(rand⟨Random A⟩);23    System.out.print(cN + " ");24}
    outputN 
  13. c ← Q

    21for (int i = 0; i < 4; i++) {22    char c→ Q = randomUppercase(rand⟨Random A⟩);23    System.out.print(cQ + " ");24}25System.out.println();2627// Random digit28System.out.println("\nRandom digits:");29for (int i = 0; i < 4; i++) {
    outputQ
    
    Random digits:
  14. for (int i = 0; i < 4; i++)

    pass 1 of 4
    28System.out.println("\nRandom digits:");29for (int i0 = 0; i < 4; i++) {30    char c = randomDigit(rand⟨Random A⟩);31    System.out.print(c + " ");
    All 4 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
  15. public static char randomDigit(Random rand)

    pass 1 of 4
    89}90public static char randomDigit(Random rand⟨Random A⟩) {91    return (char)('0' + rand.nextInt(10));92}
  16. c ← 9

    29for (int i = 0; i < 4; i++) {30    char c→ 9 = randomDigit(rand⟨Random A⟩);31    System.out.print(c9 + " ");32}
    output9 
  17. c ← 3

    29for (int i = 0; i < 4; i++) {30    char c→ 3 = randomDigit(rand⟨Random A⟩);31    System.out.print(c3 + " ");32}
    output3 
  18. c ← 2

    29for (int i = 0; i < 4; i++) {30    char c→ 2 = randomDigit(rand⟨Random A⟩);31    System.out.print(c2 + " ");32}
    output2 
  19. c ← 2

    29for (int i = 0; i < 4; i++) {30    char c→ 2 = randomDigit(rand⟨Random A⟩);31    System.out.print(c2 + " ");32}33System.out.println();3435// Random string36System.out.println("\nRandom strings:");37for (int i = 0; i < 2; i++) {
    output2
    
    Random strings:
  20. for (int i = 0; i < 2; i++)

    pass 1 of 2
    36System.out.println("\nRandom strings:");37for (int i0 = 0; i < 2; i++) {38    String s = randomString(rand⟨Random A⟩, 5);39    System.out.println("  " + s);
  21. sb ← (empty)

    pass 1 of 4
    92}93public static String randomString(Random rand⟨Random A⟩, int length5) {94    StringBuilder sb→ (empty) = new StringBuilder(length);95    for (int i = 0; i < length; i++) {
    All 4 passes — pass 1 is the card above
    passlengthsb
    15(empty)
    25(empty)
    38(empty)
    48(empty)
  22. for (int i = 0; i < length; i++)

    pass 1 of 26
    94StringBuilder sb = new StringBuilder(length);95for (int i0 = 0; i < length5; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
    26 passes — pass 1 is the card above
    passilength
    105
    215
    325
    435
    545
    605
    715
    825
    935
    ⋯ 15 more passes ⋯
    2568
    2678
  23. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  24. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  25. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  26. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  27. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  28. return sb.toString();

    97    }98    return sb.toString();99}
  29. s ← iguew

    37for (int i = 0; i < 2; i++) {38    String s→ iguew = randomString(rand⟨Random A⟩, 5);39    System.out.println("  " + siguew);40}
    output  iguew
  30. for (int i = 0; i < 2; i++)

    pass 2 of 2
    36System.out.println("\nRandom strings:");37for (int i1 = 0; i < 2; i++) {38    String s = randomString(rand⟨Random A⟩, 5);39    System.out.println("  " + s);
  31. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  32. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  33. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  34. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  35. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  36. return sb.toString();

    97    }98    return sb.toString();99}
  37. s ← ilzor

    37for (int i = 0; i < 2; i++) {38    String s→ ilzor = randomString(rand⟨Random A⟩, 5);39    System.out.println("  " + silzor);40}4142// Random alphanumeric43System.out.println("\nRandom alphanumeric:");44for (int i = 0; i < 2; i++) {
    output  ilzor
    
    Random alphanumeric:
  38. for (int i = 0; i < 2; i++)

    pass 1 of 2
    43System.out.println("\nRandom alphanumeric:");44for (int i0 = 0; i < 2; i++) {45    String s = randomAlphanumeric(rand⟨Random A⟩, 6);46    System.out.println("  " + s);
  39. chars ← ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

    pass 1 of 2
    99}100public static String randomAlphanumeric(Random rand⟨Random A⟩, int length6) {101    String chars→ ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";102    StringBuilder sb→ (empty) = new StringBuilder(length);103    for (int i = 0; i < length; i++) {
  40. for (int i = 0; i < length; i++)

    pass 1 of 12
    102StringBuilder sb = new StringBuilder(length);103for (int i0 = 0; i < length6; i++) {104    sb.append(chars.charAt(rand.nextInt(chars.length())));105}
    All 12 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    70
    81
    92
    103
    114
    125
  41. return sb.toString();

    105    }106    return sb.toString();107}
  42. s ← 6x3xGS

    44for (int i = 0; i < 2; i++) {45    String s→ 6x3xGS = randomAlphanumeric(rand⟨Random A⟩, 6);46    System.out.println("  " + s6x3xGS);47}
    output  6x3xGS
  43. for (int i = 0; i < 2; i++)

    pass 2 of 2
    43System.out.println("\nRandom alphanumeric:");44for (int i1 = 0; i < 2; i++) {45    String s = randomAlphanumeric(rand⟨Random A⟩, 6);46    System.out.println("  " + s);
  44. chars ← ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

    pass 2 of 2
    99}100public static String randomAlphanumeric(Random rand⟨Random A⟩, int length6) {101    String chars→ ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";102    StringBuilder sb→ (empty) = new StringBuilder(length);103    for (int i = 0; i < length; i++) {
  45. return sb.toString();

    105    }106    return sb.toString();107}
  46. s ← z02aWR

    44for (int i = 0; i < 2; i++) {45    String s→ z02aWR = randomAlphanumeric(rand⟨Random A⟩, 6);46    System.out.println("  " + sz02aWR);47}4849// Random password50System.out.println("\nRandom passwords:");51for (int i = 0; i < 2; i++) {
    output  z02aWR
    
    Random passwords:
  47. for (int i = 0; i < 2; i++)

    pass 1 of 2
    50System.out.println("\nRandom passwords:");51for (int i0 = 0; i < 2; i++) {52    String pwd = randomPassword(rand⟨Random A⟩, 8);53    System.out.println("  " + pwd);
  48. chars ← ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*

    pass 1 of 2
    107}108public static String randomPassword(Random rand⟨Random A⟩, int length8) {109    String chars→ ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&* = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";110    StringBuilder sb→ (empty) = new StringBuilder(length);111    for (int i = 0; i < length; i++) {
  49. for (int i = 0; i < length; i++)

    pass 1 of 16
    110StringBuilder sb = new StringBuilder(length);111for (int i0 = 0; i < length8; i++) {112    sb.append(chars.charAt(rand.nextInt(chars.length())));113}
    16 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
    90
    ⋯ 5 more passes ⋯
    156
    167
  50. return sb.toString();

    113    }114    return sb.toString();115}
  51. pwd ← R^Mh@i*F

    51for (int i = 0; i < 2; i++) {52    String pwd→ R^Mh@i*F = randomPassword(rand⟨Random A⟩, 8);53    System.out.println("  " + pwdR^Mh@i*F);54}
    output  R^Mh@i*F
  52. for (int i = 0; i < 2; i++)

    pass 2 of 2
    50System.out.println("\nRandom passwords:");51for (int i1 = 0; i < 2; i++) {52    String pwd = randomPassword(rand⟨Random A⟩, 8);53    System.out.println("  " + pwd);
  53. chars ← ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*

    pass 2 of 2
    107}108public static String randomPassword(Random rand⟨Random A⟩, int length8) {109    String chars→ ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&* = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";110    StringBuilder sb→ (empty) = new StringBuilder(length);111    for (int i = 0; i < length; i++) {
  54. return sb.toString();

    113    }114    return sb.toString();115}
  55. pwd ← @HtOb$bD

    51for (int i = 0; i < 2; i++) {52    String pwd→ @HtOb$bD = randomPassword(rand⟨Random A⟩, 8);53    System.out.println("  " + pwd@HtOb$bD);54}5556// Random hex string57System.out.println("\nRandom hex strings:");58for (int i = 0; i < 2; i++) {
    output  @HtOb$bD
    
    Random hex strings:
  56. for (int i = 0; i < 2; i++)

    pass 1 of 2
    57System.out.println("\nRandom hex strings:");58for (int i0 = 0; i < 2; i++) {59    String hex = randomHex(rand⟨Random A⟩, 8);60    System.out.println("  " + hex);
  57. hex ← 0123456789abcdef, sb ← (empty)

    pass 1 of 7
    115}116public static String randomHex(Random rand⟨Random A⟩, int length8) {117    String hex→ 0123456789abcdef = "0123456789abcdef";118    StringBuilder sb→ (empty) = new StringBuilder(length);119    for (int i = 0; i < length; i++) {
    All 7 passes — pass 1 is the card above
    passlengthhexsb
    180123456789abcdef(empty)
    280123456789abcdef(empty)
    380123456789abcdef(empty)
    440123456789abcdef(empty)
    540123456789abcdef(empty)
    640123456789abcdef(empty)
    7120123456789abcdef(empty)
  58. for (int i = 0; i < length; i++)

    pass 1 of 48
    118StringBuilder sb = new StringBuilder(length);119for (int i0 = 0; i < length8; i++) {120    sb.append(hex.charAt(rand.nextInt(16)));121}
    48 passes — pass 1 is the card above
    passilength
    108
    218
    328
    438
    548
    658
    768
    878
    908
    ⋯ 37 more passes ⋯
    471012
    481112
  59. return sb.toString();

    121    }122    return sb.toString();123}
  60. hex ← 53d06cf1

    58for (int i = 0; i < 2; i++) {59    String hex→ 53d06cf1 = randomHex(rand⟨Random A⟩, 8);60    System.out.println("  " + hex53d06cf1);61}
    output  53d06cf1
  61. for (int i = 0; i < 2; i++)

    pass 2 of 2
    57System.out.println("\nRandom hex strings:");58for (int i1 = 0; i < 2; i++) {59    String hex = randomHex(rand⟨Random A⟩, 8);60    System.out.println("  " + hex);
  62. return sb.toString();

    121    }122    return sb.toString();123}
  63. hex ← b87d43f9

    58for (int i = 0; i < 2; i++) {59    String hex→ b87d43f9 = randomHex(rand⟨Random A⟩, 8);60    System.out.println("  " + hexb87d43f9);61}6263// Random UUID-like64System.out.println("\nRandom UUID-like:");65for (int i = 0; i < 1; i++) {
    output  b87d43f9
    
    Random UUID-like:
  64. for (int i = 0; i < 1; i++)

    64System.out.println("\nRandom UUID-like:");65for (int i0 = 0; i < 1; i++) {66    String uuid = randomUUID(rand⟨Random A⟩);67    System.out.println("  " + uuid);
  65. public static String randomUUID(Random rand)

    123}124public static String randomUUID(Random rand⟨Random A⟩) {125    return String.format("%s-%s-%s-%s-%s",126        randomHex(rand⟨Random A⟩, 8),127        randomHex(rand⟨Random A⟩, 4),128        randomHex(rand⟨Random A⟩, 4),129        randomHex(rand⟨Random A⟩, 4),130        randomHex(rand⟨Random A⟩, 12)131    );132}
  66. return sb.toString();

    121    }122    return sb.toString();123}
  67. return sb.toString();

    121    }122    return sb.toString();123}
  68. return sb.toString();

    121    }122    return sb.toString();123}
  69. return sb.toString();

    121    }122    return sb.toString();123}
  70. return sb.toString();

    121    }122    return sb.toString();123}
  71. uuid ← ⟨id B⟩

    65for (int i = 0; i < 1; i++) {66    String uuid→ ⟨id B⟩ = randomUUID(rand⟨Random A⟩);67    System.out.println("  " + uuid⟨id B⟩);68}6970// Random email71System.out.println("\nRandom emails:");72for (int i = 0; i < 2; i++) {
    output  ⟨id B⟩
    
    Random emails:
  72. for (int i = 0; i < 2; i++)

    pass 1 of 2
    71System.out.println("\nRandom emails:");72for (int i0 = 0; i < 2; i++) {73    String email = randomEmail(rand⟨Random A⟩);74    System.out.println("  " + email);
  73. public static String randomEmail(Random rand)

    pass 1 of 2
    132}133public static String randomEmail(Random rand⟨Random A⟩) {134    String username = randomString(rand⟨Random A⟩, 8);135    String[] domains = {"gmail.com", "yahoo.com", "hotmail.com", "example.com"};
  74. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  75. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  76. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  77. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  78. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  79. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  80. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  81. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  82. return sb.toString();

    97    }98    return sb.toString();99}
  83. username ← qgquuvrt, domain ← yahoo.com

    133public static String randomEmail(Random rand) {134    String username→ qgquuvrt = randomString(rand⟨Random A⟩, 8);135    String[] domains = {"gmail.com", "yahoo.com", "hotmail.com", "example.com"};136    String domain→ yahoo.com = domains[rand.nextInt(domains.length4)];137    return usernameqgquuvrt + "@" + domainyahoo.com;138}
  84. email ← qgquuvrt@yahoo.com

    72for (int i = 0; i < 2; i++) {73    String email→ qgquuvrt@yahoo.com = randomEmail(rand⟨Random A⟩);74    System.out.println("  " + emailqgquuvrt@yahoo.com);75}
    output  qgquuvrt@yahoo.com
  85. for (int i = 0; i < 2; i++)

    pass 2 of 2
    71System.out.println("\nRandom emails:");72for (int i1 = 0; i < 2; i++) {73    String email = randomEmail(rand⟨Random A⟩);74    System.out.println("  " + email);
  86. public static String randomEmail(Random rand)

    pass 2 of 2
    132}133public static String randomEmail(Random rand⟨Random A⟩) {134    String username = randomString(rand⟨Random A⟩, 8);135    String[] domains = {"gmail.com", "yahoo.com", "hotmail.com", "example.com"};
  87. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  88. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  89. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  90. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  91. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  92. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  93. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  94. sb.append(randomLetter(rand));

    95for (int i = 0; i < length; i++) {96    sb.append(randomLetter(rand⟨Random A⟩));97}
  95. return sb.toString();

    97    }98    return sb.toString();99}
  96. username ← ovsqenpl, domain ← yahoo.com

    133public static String randomEmail(Random rand) {134    String username→ ovsqenpl = randomString(rand⟨Random A⟩, 8);135    String[] domains = {"gmail.com", "yahoo.com", "hotmail.com", "example.com"};136    String domain→ yahoo.com = domains[rand.nextInt(domains.length4)];137    return usernameovsqenpl + "@" + domainyahoo.com;138}
  97. email ← ovsqenpl@yahoo.com

    72for (int i = 0; i < 2; i++) {73    String email→ ovsqenpl@yahoo.com = randomEmail(rand⟨Random A⟩);74    System.out.println("  " + emailovsqenpl@yahoo.com);75}7677// Random phone number78System.out.println("\nRandom phone numbers:");79for (int i = 0; i < 2; i++) {
    output  ovsqenpl@yahoo.com
    
    Random phone numbers:
  98. for (int i = 0; i < 2; i++)

    pass 1 of 2
    78System.out.println("\nRandom phone numbers:");79for (int i0 = 0; i < 2; i++) {80    String phone = randomPhone(rand⟨Random A⟩);81    System.out.println("  " + phone);
  99. area ← 206, exchange ← 395, number ← 606

    pass 1 of 2
    138}139public static String randomPhone(Random rand⟨Random A⟩) {140    int area→ 206 = 200 + rand.nextInt(800);141    int exchange→ 395 = 200 + rand.nextInt(800);142    int number→ 606 = rand.nextInt(10000);143    return String.format("(%03d) %03d-%04d", area206, exchange395, number606);144}
  100. phone ← (206) 395-0606

    79for (int i = 0; i < 2; i++) {80    String phone→ (206) 395-0606 = randomPhone(rand⟨Random A⟩);81    System.out.println("  " + phone(206) 395-0606);82}
    output  (206) 395-0606
  101. for (int i = 0; i < 2; i++)

    pass 2 of 2
    78System.out.println("\nRandom phone numbers:");79for (int i1 = 0; i < 2; i++) {80    String phone = randomPhone(rand⟨Random A⟩);81    System.out.println("  " + phone);
  102. area ← 679, exchange ← 846, number ← 1228

    pass 2 of 2
    138}139public static String randomPhone(Random rand⟨Random A⟩) {140    int area→ 679 = 200 + rand.nextInt(800);141    int exchange→ 846 = 200 + rand.nextInt(800);142    int number→ 1228 = rand.nextInt(10000);143    return String.format("(%03d) %03d-%04d", area679, exchange846, number1228);144}
  103. phone ← (679) 846-1228

    79for (int i = 0; i < 2; i++) {80    String phone→ (679) 846-1228 = randomPhone(rand⟨Random A⟩);81    System.out.println("  " + phone(679) 846-1228);82}
    output  (679) 846-1228

Shuffling Collections

Randomly reorder elements in lists and arrays.

Shuffle.java
Replay: real traced execution (multi-file project)
// Shuffling and sampling

import java.util.*;

public class Shuffle {
    public static void main(String[] args) {
        int seed = 42;
        Random rand = new Random(seed);
        System.out.println("Seed: " + seed);

        // Shuffle list
        System.out.println("Shuffle list:");
        List<String> names = new ArrayList<>(Arrays.asList(
            "Alice", "Bob", "Charlie", "David", "Eve"
        ));
        System.out.println("Original: " + names);
        Collections.shuffle(names, rand);
        System.out.println("Shuffled: " + names);

        // Shuffle with seed (reproducible)
        System.out.println("\nShuffle with seed:");
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> nums1 = new ArrayList<>(numbers);
        List<Integer> nums2 = new ArrayList<>(numbers);

        Collections.shuffle(nums1, new Random(42));
        Collections.shuffle(nums2, new Random(42));

        System.out.println("First:  " + nums1);
        System.out.println("Second: " + nums2);
        System.out.println("Same: " + nums1.equals(nums2));

        // Shuffle array
        System.out.println("\nShuffle array:");
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println("Original: " + Arrays.toString(arr));
        shuffleArray(arr, rand);
        System.out.println("Shuffled: " + Arrays.toString(arr));

        // Pick random element
        System.out.println("\nPick random element:");
        String[] colors = {"Red", "Green", "Blue", "Yellow", "Purple"};
        for (int i = 0; i < 4; i++) {
            String color = randomChoice(colors, rand);
            System.out.print(color + " ");
        }
        System.out.println();

        // Random sample (without replacement)
        System.out.println("\nRandom sample (3 from 10):");
        List<Integer> population = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> sample = randomSample(population, 3, rand);
        System.out.println("Sample: " + sample);

        // Random sample (5 times)
        System.out.println("\nMultiple samples:");
        for (int i = 0; i < 2; i++) {
            List<Integer> s = randomSample(population, 3, rand);
            System.out.println("  " + s);
        }

        // Weighted random choice
        System.out.println("\nWeighted random choice:");
        String[] items = {"Common", "Uncommon", "Rare", "Epic"};
        double[] weights = {0.50, 0.30, 0.15, 0.05};

        int[] results = new int[items.length];
        int choices = 8;
        for (int i = 0; i < choices; i++) {
            int choice = weightedChoice(weights, rand);
            results[choice]++;
        }

        for (int i = 0; i < items.length; i++) {
            System.out.printf("%s: %d (%.1f%% expected %.1f%%)%n",
                items[i], results[i], results[i] * 100.0 / choices, weights[i] * 100);
        }

        // Random permutation
        System.out.println("\nRandom permutations:");
        List<Character> chars = Arrays.asList('A', 'B', 'C', 'D');
        for (int i = 0; i < 2; i++) {
            List<Character> perm = new ArrayList<>(chars);
            Collections.shuffle(perm, rand);
            System.out.println("  " + perm);
        }
    }
    public static void shuffleArray(int[] arr, Random rand) {
        for (int i = arr.length - 1; i > 0; i--) {
            int j = rand.nextInt(i + 1);
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    public static <T> T randomChoice(T[] arr, Random rand) {
        return arr[rand.nextInt(arr.length)];
    }
    public static <T> List<T> randomSample(List<T> population, int k, Random rand) {
        List<T> copy = new ArrayList<>(population);
        Collections.shuffle(copy, rand);
        return copy.subList(0, k);
    }
    public static int weightedChoice(double[] weights, Random rand) {
        double total = 0;
        for (double w : weights) total += w;

        double r = rand.nextDouble() * total;
        double cumulative = 0;

        for (int i = 0; i < weights.length; i++) {
            cumulative += weights[i];
            if (r < cumulative) {
                return i;
            }
        }
        return weights.length - 1;
    }

    //help h1
    // Collections.shuffle(list) - shuffle list
    // Collections.shuffle(list, random) - with custom Random
    // arr[rand.nextInt(arr.length)] - random element
    // Fisher-Yates shuffle for arrays
    // Random sample: shuffle + take first k
    // Weighted choice: cumulative probabilities
    //end
}
  1. seed ← 42, rand ← ⟨Random A⟩, names ← [Alice, Bob, Charlie, David, Eve]

    5public class Shuffle {6    public static void main(String[] args) {7        int seed→ 42 = 42;8        Random rand→ ⟨Random A⟩ = new Random(seed);9        System.out.println("Seed: " + seed42);10        11        // Shuffle list12        System.out.println("Shuffle list:");13        List<String> names→ [Alice, Bob, Charlie, David, Eve] = new ArrayList<>(Arrays.asList(14            "Alice", "Bob", "Charlie", "David", "Eve"15        ));16        System.out.println("Original: " + names[Alice, Bob, Charlie, David, Eve]);17        Collections.shuffle(names→ [Bob, Charlie, David, Eve, Alice], rand⟨Random A⟩);18        System.out.println("Shuffled: " + names[Bob, Charlie, David, Eve, Alice]);19        20        // Shuffle with seed (reproducible)21        System.out.println("\nShuffle with seed:");22        List<Integer> numbers→ [1, 2, 3, 4, 5] = Arrays.asList(1, 2, 3, 4, 5);23        List<Integer> nums1→ [1, 2, 3, 4, 5] = new ArrayList<>(numbers);24        List<Integer> nums2→ [1, 2, 3, 4, 5] = new ArrayList<>(numbers);25        26        Collections.shuffle(nums1→ [2, 3, 4, 5, 1], new Random(42));27        Collections.shuffle(nums2→ [2, 3, 4, 5, 1], new Random(42));28        29        System.out.println("First:  " + nums1[2, 3, 4, 5, 1]);30        System.out.println("Second: " + nums2[2, 3, 4, 5, 1]);31        System.out.println("Same: " + nums1.equals(nums2[2, 3, 4, 5, 1]));32        33        // Shuffle array34        System.out.println("\nShuffle array:");35        int[] arr = {1, 2, 3, 4, 5};36        System.out.println("Original: " + Arrays.toString(arr));37        shuffleArray(arr, rand⟨Random A⟩);38        System.out.println("Shuffled: " + Arrays.toString(arr));
    outputSeed: 42
    Shuffle list:
    Original: [Alice, Bob, Charlie, David, Eve]
    Shuffled: [Bob, Charlie, David, Eve, Alice]
    
    Shuffle with seed:
    First:  [2, 3, 4, 5, 1]
    Second: [2, 3, 4, 5, 1]
    Same: true
    
    Shuffle array:
    Original: [1, 2, 3, 4, 5]
  2. public static void shuffleArray(int[] arr, Random rand)

    87}88public static void shuffleArray(int[] arr, Random rand⟨Random A⟩) {89    for (int i = arr.length - 1; i > 0; i--) {
  3. j ← 0, temp ← 5, arr[i] ← 1, arr[j] ← 5

    pass 1 of 4
    88public static void shuffleArray(int[] arr, Random rand) {89    for (int i4 = arr.length5 - 1; i > 0; i--) {90        int j→ 0 = rand.nextInt(i4 + 1);91        int temp→ 5 = arr[i]5;92        arr[i]→ 1 = arr[j]1;93        arr[j]→ 5 = temp5;94    }
    All 4 passes — pass 1 is the card above
    passirandjtemparr[i]arr[j]
    14055 11 5
    233444
    322333
    41⟨Random A⟩1222
  4. for (int i = 0; i < 4; i++)

    pass 1 of 4
    42String[] colors = {"Red", "Green", "Blue", "Yellow", "Purple"};43for (int i0 = 0; i < 4; i++) {44    String color = randomChoice(colors, rand⟨Random A⟩);45    System.out.print(color + " ");
    All 4 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
  5. public static <T> T randomChoice(T[] arr, Random rand)

    pass 1 of 4
    95}96public static <T> T randomChoice(T[] arr, Random rand⟨Random A⟩) {97    return arr[rand.nextInt(arr.length5)];98}
  6. color ← Purple

    43for (int i = 0; i < 4; i++) {44    String color→ Purple = randomChoice(colors, rand⟨Random A⟩);45    System.out.print(colorPurple + " ");46}
    outputPurple 
  7. color ← Yellow

    43for (int i = 0; i < 4; i++) {44    String color→ Yellow = randomChoice(colors, rand⟨Random A⟩);45    System.out.print(colorYellow + " ");46}
    outputYellow 
  8. color ← Blue

    43for (int i = 0; i < 4; i++) {44    String color→ Blue = randomChoice(colors, rand⟨Random A⟩);45    System.out.print(colorBlue + " ");46}
    outputBlue 
  9. color ← Blue, population ← [1, 2, 3, 4, 5]

    43for (int i = 0; i < 4; i++) {44    String color→ Blue = randomChoice(colors, rand⟨Random A⟩);45    System.out.print(colorBlue + " ");46}47System.out.println();4849// Random sample (without replacement)50System.out.println("\nRandom sample (3 from 10):");51List<Integer> population→ [1, 2, 3, 4, 5] = Arrays.asList(1, 2, 3, 4, 5);52List<Integer> sample = randomSample(population[1, 2, 3, 4, 5], 3, rand⟨Random A⟩);53System.out.println("Sample: " + sample);
    outputBlue
    
    Random sample (3 from 10):
  10. copy ← [1, 2, 3, 4, 5]

    pass 1 of 3
    98}99public static <T> List<T> randomSample(List<T> population[1, 2, 3, 4, 5], int k3, Random rand⟨Random A⟩) {100    List<T> copy→ [1, 2, 3, 4, 5] = new ArrayList<>(population);101    Collections.shuffle(copy→ [1, 4, 3, 5, 2], rand⟨Random A⟩);102    return copy.subList(0, k3);103}
    All 3 passes — pass 1 is the card above
    passcopy
    1[1, 2, 3, 4, 5]
    2[1, 2, 3, 4, 5]
    3[1, 2, 3, 4, 5]
  11. sample ← [1, 4, 3]

    51List<Integer> population = Arrays.asList(1, 2, 3, 4, 5);52List<Integer> sample→ [1, 4, 3] = randomSample(population[1, 2, 3, 4, 5], 3, rand⟨Random A⟩);53System.out.println("Sample: " + sample[1, 4, 3]);5455// Random sample (5 times)56System.out.println("\nMultiple samples:");57for (int i = 0; i < 2; i++) {
    outputSample: [1, 4, 3]
    
    Multiple samples:
  12. for (int i = 0; i < 2; i++)

    pass 1 of 2
    56System.out.println("\nMultiple samples:");57for (int i0 = 0; i < 2; i++) {58    List<Integer> s = randomSample(population[1, 2, 3, 4, 5], 3, rand⟨Random A⟩);59    System.out.println("  " + s);
  13. s ← [1, 3, 5]

    57for (int i = 0; i < 2; i++) {58    List<Integer> s→ [1, 3, 5] = randomSample(population[1, 2, 3, 4, 5], 3, rand⟨Random A⟩);59    System.out.println("  " + s[1, 3, 5]);60}
    output  [1, 3, 5]
  14. for (int i = 0; i < 2; i++)

    pass 2 of 2
    56System.out.println("\nMultiple samples:");57for (int i1 = 0; i < 2; i++) {58    List<Integer> s = randomSample(population[1, 2, 3, 4, 5], 3, rand⟨Random A⟩);59    System.out.println("  " + s);
  15. s ← [2, 4, 3], choices ← 8

    57for (int i = 0; i < 2; i++) {58    List<Integer> s→ [2, 4, 3] = randomSample(population[1, 2, 3, 4, 5], 3, rand⟨Random A⟩);59    System.out.println("  " + s[2, 4, 3]);60}6162// Weighted random choice63System.out.println("\nWeighted random choice:");64String[] items = {"Common", "Uncommon", "Rare", "Epic"};65double[] weights = {0.50, 0.30, 0.15, 0.05};6667int[] results = new int[items.length4];68int choices→ 8 = 8;69for (int i = 0; i < choices; i++) {
    output  [2, 4, 3]
    
    Weighted random choice:
  16. for (int i = 0; i < choices; i++)

    pass 1 of 8
    68int choices = 8;69for (int i0 = 0; i < choices8; i++) {70    int choice = weightedChoice(weights, rand⟨Random A⟩);71    results[choice]++;
    All 8 passes — pass 1 is the card above
    passi
    10
    21
    32
    43
    54
    65
    76
    87
  17. total ← 0.0

    pass 1 of 8
    103}104public static int weightedChoice(double[] weights, Random rand⟨Random A⟩) {105    double total→ 0.0 = 0;106    for (double w : weights) total += w;
    All 8 passes — pass 1 is the card above
    passtotal
    10.0
    20.0
    30.0
    40.0
    50.0
    60.0
    70.0
    80.0
  18. total ← 0.5

    pass 1 of 32
    105double total = 0;106for (double w0.5 : weights) total→ 0.5 += w;
    32 passes — pass 1 is the card above
    passwtotal
    10.50.0 0.5
    20.30.5 0.8
    30.150.8 0.9500000000000001
    40.050.9500000000000001 1.0
    50.50.0 0.5
    60.30.5 0.8
    70.150.8 0.9500000000000001
    80.050.9500000000000001 1.0
    90.50.0 0.5
    ⋯ 21 more passes ⋯
    310.150.8 0.9500000000000001
    320.050.9500000000000001 1.0
  19. r ← 0.7499061812554475, cumulative ← 0.0

    108double r→ 0.7499061812554475 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;
  20. cumulative ← 0.5

    pass 1 of 13
    111for (int i0 = 0; i < weights.length4; i++) {112    cumulative→ 0.5 += weights[i]0.5;113    if (r < cumulative) {
    13 passes — pass 1 is the card above
    passiweights[i]cumulative
    100.50.0 0.5
    210.30.5 0.8
    300.50.0 0.5
    400.50.0 0.5
    500.50.0 0.5
    610.30.5 0.8
    700.50.0 0.5
    800.50.0 0.5
    910.30.5 0.8
    ⋯ 2 more passes ⋯
    1200.50.0 0.5
    1310.30.5 0.8
  21. if (r < cumulative)

    pass 1 of 8
    112cumulative += weights[i];113if (r0.7499061812554475 < cumulative0.8) {114    return i1;115}
    All 8 passes — pass 1 is the card above
    passrcumulativei
    10.74990618125544750.81
    20.386566874359348670.50
    30.177378477909378330.50
    40.59434991088968410.81
    50.209767568866332080.50
    60.8259658718878210.95000000000000012
    70.172217937687852430.50
    80.58742738178629560.81
  22. choice ← 1, results[choice] ← 1

    69for (int i = 0; i < choices; i++) {70    int choice→ 1 = weightedChoice(weights, rand⟨Random A⟩);71    results[choice]→ 1++;72}
  23. r ← 0.38656687435934867, cumulative ← 0.0

    108double r→ 0.38656687435934867 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;
  24. choice ← 0, results[choice] ← 1

    69for (int i = 0; i < choices; i++) {70    int choice→ 0 = weightedChoice(weights, rand⟨Random A⟩);71    results[choice]→ 1++;72}
  25. r ← 0.17737847790937833, cumulative ← 0.0

    108double r→ 0.17737847790937833 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;
  26. choice ← 0, results[choice] ← 2

    69for (int i = 0; i < choices; i++) {70    int choice→ 0 = weightedChoice(weights, rand⟨Random A⟩);71    results[choice]→ 2++;72}
  27. r ← 0.5943499108896841, cumulative ← 0.0

    108double r→ 0.5943499108896841 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;
  28. choice ← 1, results[choice] ← 2

    69for (int i = 0; i < choices; i++) {70    int choice→ 1 = weightedChoice(weights, rand⟨Random A⟩);71    results[choice]→ 2++;72}
  29. r ← 0.20976756886633208, cumulative ← 0.0

    108double r→ 0.20976756886633208 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;
  30. choice ← 0, results[choice] ← 3

    69for (int i = 0; i < choices; i++) {70    int choice→ 0 = weightedChoice(weights, rand⟨Random A⟩);71    results[choice]→ 3++;72}
  31. r ← 0.825965871887821, cumulative ← 0.0

    108double r→ 0.825965871887821 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;
  32. choice ← 2, results[choice] ← 1

    69for (int i = 0; i < choices; i++) {70    int choice→ 2 = weightedChoice(weights, rand⟨Random A⟩);71    results[choice]→ 1++;72}
  33. r ← 0.17221793768785243, cumulative ← 0.0

    108double r→ 0.17221793768785243 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;
  34. choice ← 0, results[choice] ← 4

    69for (int i = 0; i < choices; i++) {70    int choice→ 0 = weightedChoice(weights, rand⟨Random A⟩);71    results[choice]→ 4++;72}
  35. r ← 0.5874273817862956, cumulative ← 0.0

    108double r→ 0.5874273817862956 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;
  36. choice ← 1, results[choice] ← 3

    69for (int i = 0; i < choices; i++) {70    int choice→ 1 = weightedChoice(weights, rand⟨Random A⟩);71    results[choice]→ 3++;72}
  37. for (int i = 0; i < items.length; i++)

    pass 1 of 4
    74for (int i0 = 0; i < items.length4; i++) {75    System.out.printf("%s: %d (%.1f%% expected %.1f%%)%n",76        items[i]Common, results[i]4, results[i] * 100.0 / choices8, weights[i]0.5 * 100);77}
    All 4 passes — pass 1 is the card above
    passiitems[i]results[i]weights[i]
    10Common40.5
    21Uncommon30.3
    32Rare10.15
    43Epic00.05
  38. chars ← [A, B, C, D]

    79// Random permutation80System.out.println("\nRandom permutations:");81List<Character> chars→ [A, B, C, D] = Arrays.asList('A', 'B', 'C', 'D');82for (int i = 0; i < 2; i++) {
    output
    Random permutations:
  39. perm ← [A, B, C, D]

    pass 1 of 2
    81List<Character> chars = Arrays.asList('A', 'B', 'C', 'D');82for (int i0 = 0; i < 2; i++) {83    List<Character> perm→ [A, B, C, D] = new ArrayList<>(chars);84    Collections.shuffle(perm→ [A, C, B, D], rand⟨Random A⟩);85    System.out.println("  " + perm[A, C, B, D]);86}
    output  [A, C, B, D]
  40. perm ← [A, B, C, D]

    pass 2 of 2
    81List<Character> chars = Arrays.asList('A', 'B', 'C', 'D');82for (int i1 = 0; i < 2; i++) {83    List<Character> perm→ [A, B, C, D] = new ArrayList<>(chars);84    Collections.shuffle(perm→ [B, D, C, A], rand⟨Random A⟩);85    System.out.println("  " + perm[B, D, C, A]);86}
    output  [B, D, C, A]

@seealso math_functions

Exercise: Practical.java

Simulate rolling dice and generate a random password