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.

Basic Usage

Create a Random instance and generate numbers.

Basic.java
// 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 = ;
        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 = ;
        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 = ;
        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
}
Pseudo-random Numbers generated by a deterministic algorithm that appear random but are reproducible when given the same seed.
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
// 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
}

Random Distributions

Generate numbers following different statistical distributions.

Distributions.java
// 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
}
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
// 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
}

Shuffling Collections

Randomly reorder elements in lists and arrays.

Shuffle.java
// 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
}

@seealso math_functions

Exercise: Practical.java

Simulate rolling dice and generate a random password