Math & Numbers
Random Number Generation
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.
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
}
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:for (int i = 0; i < 5; i++)
pass 1 of 513System.out.println("Random integers:");14for (int i0 = 0; i < 5; i++) {15 System.out.println(" " + rand.nextInt());16}output -1170105035All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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):for (int i = 0; i < 5; i++)
pass 1 of 519System.out.println("\nRandom int [0, 100):");20for (int i0 = 0; i < 5; i++) {21 System.out.println(" " + rand.nextInt(100));22}output 25All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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:for (int i = 0; i < 5; i++)
pass 1 of 525System.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 pass i1 0 2 1 3 2 4 3 5 4 System.out.println(" Random booleans:");
30// Random booleans31System.out.println("\nRandom booleans:");32for (int i = 0; i < 10; i++) {output Random booleans:for (int i = 0; i < 10; i++)
pass 1 of 1031System.out.println("\nRandom booleans:");32for (int i0 = 0; i < 10; i++) {33 System.out.print(rand.nextBoolean() ? "T " : "F ");34}outputTAll 10 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 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:for (int i = 0; i < 3; i++)
pass 1 of 338System.out.println("\nRandom longs:");39for (int i0 = 0; i < 3; i++) {40 System.out.println(" " + rand.nextLong());41}output -7482923245497525943All 3 passes — pass 1 is the card above pass i1 0 2 1 3 2 System.out.println(" Random floats:");
43// Random floats44System.out.println("\nRandom floats:");45for (int i = 0; i < 5; i++) {output Random floats:for (int i = 0; i < 5; i++)
pass 1 of 544System.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 pass i1 0 2 1 3 2 4 3 5 4 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):for (int i = 0; i < 10; i++)
pass 1 of 1050System.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 pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 9 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:for (int i = 0; i < 5; i++)
pass 1 of 560System.out.println("First sequence:");61for (int i0 = 0; i < 5; i++) {62 System.out.println(" " + seeded1.nextInt(100));63}output 30All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 System.out.println("Second sequence (same):");
65System.out.println("Second sequence (same):");66for (int i = 0; i < 5; i++) {outputSecond sequence (same):for (int i = 0; i < 5; i++)
pass 1 of 565System.out.println("Second sequence (same):");66for (int i0 = 0; i < 5; i++) {67 System.out.println(" " + seeded2.nextInt(100));68}output 30All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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:for (int i = 0; i < 5; i++)
pass 1 of 572Random separate = new Random(seed + 1);73for (int i0 = 0; i < 5; i++) {74 System.out.println(" " + separate.nextInt(100));75}output 56All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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():r ← 0.3784287179875597
pass 1 of 578System.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 pass ir1 0 0.3784287179875597 2 1 0.13642362296961053 3 2 0.4362829094329638 4 3 0.6487936445670887 5 4 0.6959691863162578 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):min ← 10, max ← 20, r ← 19
pass 1 of 585System.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 19All 5 passes — pass 1 is the card above pass iminmaxr1 0 10 20 19 2 1 10 20 15 3 2 10 20 10 4 3 10 20 10 5 4 10 20 17 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:for (byte b : bytes)
pass 1 of 1096rand.nextBytes(bytes);97for (byte b-97 : bytes) {98 System.out.printf("%3d ", b-97);99}All 10 passes — pass 1 is the card above pass b1 -97 2 91 3 -31 4 -62 5 -57 6 -112 7 -45 8 71 9 -128 10 26 System.out.println();
99 }100 System.out.println();101}
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:for (int i = 0; i < 5; i++)
pass 1 of 513System.out.println("Random integers:");14for (int i0 = 0; i < 5; i++) {15 System.out.println(" " + rand.nextInt());16}output -1156638823All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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):for (int i = 0; i < 5; i++)
pass 1 of 519System.out.println("\nRandom int [0, 100):");20for (int i0 = 0; i < 5; i++) {21 System.out.println(" " + rand.nextInt(100));22}output 54All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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:for (int i = 0; i < 5; i++)
pass 1 of 525System.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 pass i1 0 2 1 3 2 4 3 5 4 System.out.println(" Random booleans:");
30// Random booleans31System.out.println("\nRandom booleans:");32for (int i = 0; i < 10; i++) {output Random booleans:for (int i = 0; i < 10; i++)
pass 1 of 1031System.out.println("\nRandom booleans:");32for (int i0 = 0; i < 10; i++) {33 System.out.print(rand.nextBoolean() ? "T " : "F ");34}outputTAll 10 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 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:for (int i = 0; i < 3; i++)
pass 1 of 338System.out.println("\nRandom longs:");39for (int i0 = 0; i < 3; i++) {40 System.out.println(" " + rand.nextLong());41}output 7058350309194143667All 3 passes — pass 1 is the card above pass i1 0 2 1 3 2 System.out.println(" Random floats:");
43// Random floats44System.out.println("\nRandom floats:");45for (int i = 0; i < 5; i++) {output Random floats:for (int i = 0; i < 5; i++)
pass 1 of 544System.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 pass i1 0 2 1 3 2 4 3 5 4 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):for (int i = 0; i < 10; i++)
pass 1 of 1050System.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 pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 9 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:for (int i = 0; i < 5; i++)
pass 1 of 560System.out.println("First sequence:");61for (int i0 = 0; i < 5; i++) {62 System.out.println(" " + seeded1.nextInt(100));63}output 36All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 System.out.println("Second sequence (same):");
65System.out.println("Second sequence (same):");66for (int i = 0; i < 5; i++) {outputSecond sequence (same):for (int i = 0; i < 5; i++)
pass 1 of 565System.out.println("Second sequence (same):");66for (int i0 = 0; i < 5; i++) {67 System.out.println(" " + seeded2.nextInt(100));68}output 36All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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:for (int i = 0; i < 5; i++)
pass 1 of 572Random separate = new Random(seed + 1);73for (int i0 = 0; i < 5; i++) {74 System.out.println(" " + separate.nextInt(100));75}output 64All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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():r ← 0.914050901118219
pass 1 of 578System.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 pass ir1 0 0.914050901118219 2 1 0.04602627126135539 3 2 0.011618108144987094 4 3 0.9869525209966808 5 4 0.324051006646354 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):min ← 10, max ← 20, r ← 13
pass 1 of 585System.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 13All 5 passes — pass 1 is the card above pass iminmaxr1 0 10 20 13 2 1 10 20 13 3 2 10 20 14 4 3 10 20 10 5 4 10 20 11 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:for (byte b : bytes)
pass 1 of 1096rand.nextBytes(bytes);97for (byte b-4 : bytes) {98 System.out.printf("%3d ", b-4);99}All 10 passes — pass 1 is the card above pass b1 -4 2 -18 3 -128 4 -18 5 -3 6 7 7 -83 8 65 9 101 10 83 System.out.println();
99 }100 System.out.println();101}
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:for (int i = 0; i < 5; i++)
pass 1 of 513System.out.println("Random integers:");14for (int i0 = 0; i < 5; i++) {15 System.out.println(" " + rand.nextInt());16}output 1553932502All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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):for (int i = 0; i < 5; i++)
pass 1 of 519System.out.println("\nRandom int [0, 100):");20for (int i0 = 0; i < 5; i++) {21 System.out.println(" " + rand.nextInt(100));22}output 84All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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:for (int i = 0; i < 5; i++)
pass 1 of 525System.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 pass i1 0 2 1 3 2 4 3 5 4 System.out.println(" Random booleans:");
30// Random booleans31System.out.println("\nRandom booleans:");32for (int i = 0; i < 10; i++) {output Random booleans:for (int i = 0; i < 10; i++)
pass 1 of 1031System.out.println("\nRandom booleans:");32for (int i0 = 0; i < 10; i++) {33 System.out.print(rand.nextBoolean() ? "T " : "F ");34}outputTAll 10 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 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:for (int i = 0; i < 3; i++)
pass 1 of 338System.out.println("\nRandom longs:");39for (int i0 = 0; i < 3; i++) {40 System.out.println(" " + rand.nextLong());41}output -5671795673574091253All 3 passes — pass 1 is the card above pass i1 0 2 1 3 2 System.out.println(" Random floats:");
43// Random floats44System.out.println("\nRandom floats:");45for (int i = 0; i < 5; i++) {output Random floats:for (int i = 0; i < 5; i++)
pass 1 of 544System.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 pass i1 0 2 1 3 2 4 3 5 4 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):for (int i = 0; i < 10; i++)
pass 1 of 1050System.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 pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 9 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:for (int i = 0; i < 5; i++)
pass 1 of 560System.out.println("First sequence:");61for (int i0 = 0; i < 5; i++) {62 System.out.println(" " + seeded1.nextInt(100));63}output 51All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 System.out.println("Second sequence (same):");
65System.out.println("Second sequence (same):");66for (int i = 0; i < 5; i++) {outputSecond sequence (same):for (int i = 0; i < 5; i++)
pass 1 of 565System.out.println("Second sequence (same):");66for (int i0 = 0; i < 5; i++) {67 System.out.println(" " + seeded2.nextInt(100));68}output 51All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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:for (int i = 0; i < 5; i++)
pass 1 of 572Random separate = new Random(seed + 1);73for (int i0 = 0; i < 5; i++) {74 System.out.println(" " + separate.nextInt(100));75}output 74All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 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():r ← 0.5141767124330875
pass 1 of 578System.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 pass ir1 0 0.5141767124330875 2 1 0.5173344627422577 3 2 0.0054778097797331116 4 3 0.11451624896785961 5 4 0.1514197810837441 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):min ← 10, max ← 20, r ← 11
pass 1 of 585System.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 11All 5 passes — pass 1 is the card above pass iminmaxr1 0 10 20 11 2 1 10 20 18 3 2 10 20 14 4 3 10 20 13 5 4 10 20 19 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:for (byte b : bytes)
pass 1 of 1096rand.nextBytes(bytes);97for (byte b-120 : bytes) {98 System.out.printf("%3d ", b-120);99}All 10 passes — pass 1 is the card above pass b1 -120 2 98 3 86 4 30 5 80 6 125 7 68 8 -10 9 40 10 24 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
}
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]:public static int randInt(Random rand, int min, int max)
pass 1 of 551}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 pass minmax1 10 20 2 0 50 3 -10 10 4 1 6 5 1 6 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]: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]: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]:public static double randDouble(Random rand, double min, double max)
pass 1 of 254}55public static double randDouble(Random rand⟨Random A⟩, double min0.0, double max10.0) {56 return min0.0 + (max10.0 - min) * rand.nextDouble();57}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]:public static double randDouble(Random rand, double min, double max)
pass 2 of 254}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}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: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);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
}
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):bin ← 1, uniform[bin] ← 1
pass 1 of 814int[] 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 pass ibinuniform[bin]1 0 1 0 → 1 2 1 3 0 → 1 3 2 2 0 → 1 4 3 4 0 → 1 5 4 3 1 → 2 6 5 1 1 → 2 7 6 0 0 → 1 8 7 0 1 → 2 printHistogram("Uniform", uniform, samples);
18}19printHistogram("Uniform", uniform, samples8);public static void printHistogram(String name, int[] bins, int total)
pass 1 of 4104}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 pass name1 Uniform 2 Gaussian 3 Exponential 4 Triangle percent ← 25, bar ← █████████████████████████
pass 1 of 20105public 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 pass ibins[i]samplespercentbar1 0 2 — 25 █████████████████████████ 2 1 2 — 25 █████████████████████████ 3 2 1 — 12 ████████████ 4 3 2 — 25 █████████████████████████ 5 4 1 8 12 ████████████ 6 0 0 — 0 (empty) 7 1 1 — 12 ████████████ 8 2 6 — 75 ███████████████████████████████████████████████████████████████████████████ 9 3 1 — 12 ████████████ ⋯ 9 more passes ⋯ 19 3 3 — 37 █████████████████████████████████████ 20 4 0 8 0 (empty) value ← 52.8097763807278, bin ← 2, gaussian[bin] ← 1
pass 1 of 823int[] 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 pass ivaluebingaussian[bin]1 0 52.8097763807278 2 0 → 1 2 1 56.84622795632655 2 1 → 2 3 2 41.82778592601273 2 2 → 3 4 3 36.03356597321957 1 0 → 1 5 4 48.090554869291246 2 3 → 4 6 5 64.8621339239065 3 0 → 1 7 6 58.02307149687363 2 4 → 5 8 7 48.78487075334507 2 5 → 6 printHistogram("Gaussian", gaussian, samples);
28}29printHistogram("Gaussian", gaussian, samples8);for (int i = 0; i < samples; i++)
pass 1 of 833int[] 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 pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 public static double exponentialRandom(Random rand, double lambda)
pass 1 of 879}80public static double exponentialRandom(Random rand⟨Random A⟩, double lambda0.1) {81 return -Math.log(1 - rand.nextDouble()) / lambda0.1;82}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}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}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}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}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}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}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}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);heads ← 0
pass 1 of 843int[] 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 pass iheads1 0 0 2 1 0 3 2 0 4 3 0 5 4 0 6 5 0 7 6 0 8 7 0 for (int j = 0; j < 10; j++)
pass 1 of 8045int heads = 0;46for (int j0 = 0; j < 10; j++) {47 if (rand.nextBoolean()) heads++;80 passes — pass 1 is the card above pass j1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 ⋯ 69 more passes ⋯ 79 8 80 9 heads ← 1
pass 1 of 3646for (int j = 0; j < 10; j++) {47 if (rand.nextBoolean()) heads→ 1++;48}36 passes — pass 1 is the card above pass heads1 0 → 1 2 1 → 2 3 2 → 3 4 3 → 4 5 4 → 5 6 5 → 6 7 0 → 1 8 1 → 2 9 2 → 3 ⋯ 25 more passes ⋯ 35 1 → 2 36 2 → 3 binomial[heads] ← 1
48 }49 binomial[heads]→ 1++;50}values this step6headsbinomial[heads] ← 1
48 }49 binomial[heads]→ 1++;50}values this step5headsbinomial[heads] ← 2
48 }49 binomial[heads]→ 2++;50}values this step5headsbinomial[heads] ← 1
48 }49 binomial[heads]→ 1++;50}values this step3headsbinomial[heads] ← 3
48 }49 binomial[heads]→ 3++;50}values this step5headsbinomial[heads] ← 1
48 }49 binomial[heads]→ 1++;50}values this step4headsbinomial[heads] ← 4
48 }49 binomial[heads]→ 4++;50}values this step5headsbinomial[heads] ← 2
48 }49 binomial[heads]→ 2++;50}values this step3headsSystem.out.println("Number of heads:");
50}51System.out.println("Number of heads:");52for (int i = 0; i <= 10; i++) {outputNumber of heads:for (int i = 0; i <= 10; i++)
pass 1 of 1151System.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 pass ibinomial[i]1 0 0 2 1 0 3 2 0 4 3 2 5 4 1 6 5 4 7 6 1 8 7 0 9 8 0 10 9 0 11 10 0 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:for (int i = 0; i < samples; i++)
pass 1 of 858int[] 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 pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 L ← 0.006737946999085467, k ← 0, p ← 1.0
pass 1 of 882}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 pass Lkp1 0.006737946999085467 0 1.0 2 0.006737946999085467 0 1.0 3 0.006737946999085467 0 1.0 4 0.006737946999085467 0 1.0 5 0.006737946999085467 0 1.0 6 0.006737946999085467 0 1.0 7 0.006737946999085467 0 1.0 8 0.006737946999085467 0 1.0 k ← 1, p ← 0.6972487292697295
pass 1 of 4588do {89 k→ 1++;90 p→ 0.6972487292697295 *= rand.nextDouble();91} while (p > L);45 passes — pass 1 is the card above pass kp1 0 → 1 1.0 → 0.6972487292697295 2 1 → 2 0.6972487292697295 → 0.6335303614456775 3 2 → 3 0.6335303614456775 → 0.1242651253458207 4 3 → 4 0.1242651253458207 → 0.10054599677108673 5 4 → 5 0.10054599677108673 → 0.06313617708218094 6 5 → 6 0.06313617708218094 → 0.02925725843539916 7 6 → 7 0.02925725843539916 → 0.008940408329833621 8 7 → 8 0.008940408329833621 → 0.004827010803408223 9 0 → 1 1.0 → 0.6351110144563881 ⋯ 34 more passes ⋯ 44 4 → 5 0.13541228243409476 → 0.046573991075327725 45 5 → 6 0.046573991075327725 → 6.546355631740219E-4 return k - 1;
93 return k8 - 1;94}events ← 7
59for (int i = 0; i < samples; i++) {60 int events→ 7 = poissonRandom(rand⟨Random A⟩, 5.0);61 if (events < poisson.length) {poisson[events] ← 1
pass 1 of 860int events = poissonRandom(rand, 5.0);61if (events7 < poisson.length15) {62 poisson[events]→ 1++;63}All 8 passes — pass 1 is the card above pass eventspoisson[events]1 7 0 → 1 2 3 0 → 1 3 3 1 → 2 4 8 0 → 1 5 5 0 → 1 6 3 2 → 3 7 3 3 → 4 8 5 1 → 2 return k - 1;
93 return k4 - 1;94}events ← 3
59for (int i = 0; i < samples; i++) {60 int events→ 3 = poissonRandom(rand⟨Random A⟩, 5.0);61 if (events < poisson.length) {return k - 1;
93 return k4 - 1;94}events ← 3
59for (int i = 0; i < samples; i++) {60 int events→ 3 = poissonRandom(rand⟨Random A⟩, 5.0);61 if (events < poisson.length) {return k - 1;
93 return k9 - 1;94}events ← 8
59for (int i = 0; i < samples; i++) {60 int events→ 8 = poissonRandom(rand⟨Random A⟩, 5.0);61 if (events < poisson.length) {return k - 1;
93 return k6 - 1;94}events ← 5
59for (int i = 0; i < samples; i++) {60 int events→ 5 = poissonRandom(rand⟨Random A⟩, 5.0);61 if (events < poisson.length) {return k - 1;
93 return k4 - 1;94}events ← 3
59for (int i = 0; i < samples; i++) {60 int events→ 3 = poissonRandom(rand⟨Random A⟩, 5.0);61 if (events < poisson.length) {return k - 1;
93 return k4 - 1;94}events ← 3
59for (int i = 0; i < samples; i++) {60 int events→ 3 = poissonRandom(rand⟨Random A⟩, 5.0);61 if (events < poisson.length) {return k - 1;
93 return k6 - 1;94}events ← 5
59for (int i = 0; i < samples; i++) {60 int events→ 5 = poissonRandom(rand⟨Random A⟩, 5.0);61 if (events < poisson.length) {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:for (int i = 0; i < Math.min(12, poisson.length); i++)
pass 1 of 1265System.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 pass ipoisson[i]1 0 0 2 1 0 3 2 0 4 3 4 5 4 0 6 5 2 7 6 0 8 7 1 9 8 1 10 9 0 11 10 0 12 11 0 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]:for (int i = 0; i < samples; i++)
pass 1 of 872int[] 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 pass iucminmaxmode1 0 — — — — — 2 1 — — — — — 3 2 — — — — — 4 3 — — — — — 5 4 — — — — — 6 5 — — — — — 7 6 0.1157501237196259 0.5 0.0 100.0 50.0 8 7 — — — — — u ← 0.8095941248100625, c ← 0.5
pass 1 of 894}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 pass uc1 0.8095941248100625 0.5 2 0.5214943036897558 0.5 3 0.835155555007701 0.5 4 0.5834616485911189 0.5 5 0.6882460693475149 0.5 6 0.5563822013190519 0.5 7 0.1157501237196259 0.5 8 0.5885086368942899 0.5 else
pass 1 of 7100 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 pass u1 0.8095941248100625 2 0.5214943036897558 3 0.835155555007701 4 0.5834616485911189 5 0.6882460693475149 6 0.5563822013190519 7 0.5885086368942899 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}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}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}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}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}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}if (u < c)
99if (u0.1157501237196259 < c0.5) {100 return min0.0 + Math.sqrt(u0.1157501237196259 * (max100.0 - min) * (mode50.0 - min));101} else {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}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
}
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:for (int i = 0; i < 4; i++)
pass 1 of 412System.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 pass i1 0 2 1 3 2 4 3 public static char randomLetter(Random rand)
pass 1 of 3083}84public static char randomLetter(Random rand⟨Random A⟩) {85 return (char)('a' + rand.nextInt(26));86}c ← a
13for (int i = 0; i < 4; i++) {14 char c→ a = randomLetter(rand⟨Random A⟩);15 System.out.print(ca + " ");16}outputac ← h
13for (int i = 0; i < 4; i++) {14 char c→ h = randomLetter(rand⟨Random A⟩);15 System.out.print(ch + " ");16}outputhc ← w
13for (int i = 0; i < 4; i++) {14 char c→ w = randomLetter(rand⟨Random A⟩);15 System.out.print(cw + " ");16}outputwc ← 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:for (int i = 0; i < 4; i++)
pass 1 of 420System.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 pass i1 0 2 1 3 2 4 3 public static char randomUppercase(Random rand)
pass 1 of 486}87public static char randomUppercase(Random rand⟨Random A⟩) {88 return (char)('A' + rand.nextInt(26));89}c ← A
21for (int i = 0; i < 4; i++) {22 char c→ A = randomUppercase(rand⟨Random A⟩);23 System.out.print(cA + " ");24}outputAc ← R
21for (int i = 0; i < 4; i++) {22 char c→ R = randomUppercase(rand⟨Random A⟩);23 System.out.print(cR + " ");24}outputRc ← N
21for (int i = 0; i < 4; i++) {22 char c→ N = randomUppercase(rand⟨Random A⟩);23 System.out.print(cN + " ");24}outputNc ← 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:for (int i = 0; i < 4; i++)
pass 1 of 428System.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 pass i1 0 2 1 3 2 4 3 public static char randomDigit(Random rand)
pass 1 of 489}90public static char randomDigit(Random rand⟨Random A⟩) {91 return (char)('0' + rand.nextInt(10));92}c ← 9
29for (int i = 0; i < 4; i++) {30 char c→ 9 = randomDigit(rand⟨Random A⟩);31 System.out.print(c9 + " ");32}output9c ← 3
29for (int i = 0; i < 4; i++) {30 char c→ 3 = randomDigit(rand⟨Random A⟩);31 System.out.print(c3 + " ");32}output3c ← 2
29for (int i = 0; i < 4; i++) {30 char c→ 2 = randomDigit(rand⟨Random A⟩);31 System.out.print(c2 + " ");32}output2c ← 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:for (int i = 0; i < 2; i++)
pass 1 of 236System.out.println("\nRandom strings:");37for (int i0 = 0; i < 2; i++) {38 String s = randomString(rand⟨Random A⟩, 5);39 System.out.println(" " + s);sb ← (empty)
pass 1 of 492}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 pass lengthsb1 5 (empty) 2 5 (empty) 3 8 (empty) 4 8 (empty) for (int i = 0; i < length; i++)
pass 1 of 2694StringBuilder 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 pass ilength1 0 5 2 1 5 3 2 5 4 3 5 5 4 5 6 0 5 7 1 5 8 2 5 9 3 5 ⋯ 15 more passes ⋯ 25 6 8 26 7 8 sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}return sb.toString();
97 }98 return sb.toString();99}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 iguewfor (int i = 0; i < 2; i++)
pass 2 of 236System.out.println("\nRandom strings:");37for (int i1 = 0; i < 2; i++) {38 String s = randomString(rand⟨Random A⟩, 5);39 System.out.println(" " + s);sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}return sb.toString();
97 }98 return sb.toString();99}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:for (int i = 0; i < 2; i++)
pass 1 of 243System.out.println("\nRandom alphanumeric:");44for (int i0 = 0; i < 2; i++) {45 String s = randomAlphanumeric(rand⟨Random A⟩, 6);46 System.out.println(" " + s);chars ← ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
pass 1 of 299}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++) {for (int i = 0; i < length; i++)
pass 1 of 12102StringBuilder 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 pass i1 0 2 1 3 2 4 3 5 4 6 5 7 0 8 1 9 2 10 3 11 4 12 5 return sb.toString();
105 }106 return sb.toString();107}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 6x3xGSfor (int i = 0; i < 2; i++)
pass 2 of 243System.out.println("\nRandom alphanumeric:");44for (int i1 = 0; i < 2; i++) {45 String s = randomAlphanumeric(rand⟨Random A⟩, 6);46 System.out.println(" " + s);chars ← ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
pass 2 of 299}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++) {return sb.toString();
105 }106 return sb.toString();107}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:for (int i = 0; i < 2; i++)
pass 1 of 250System.out.println("\nRandom passwords:");51for (int i0 = 0; i < 2; i++) {52 String pwd = randomPassword(rand⟨Random A⟩, 8);53 System.out.println(" " + pwd);chars ← ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*
pass 1 of 2107}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++) {for (int i = 0; i < length; i++)
pass 1 of 16110StringBuilder 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 pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 0 ⋯ 5 more passes ⋯ 15 6 16 7 return sb.toString();
113 }114 return sb.toString();115}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*Ffor (int i = 0; i < 2; i++)
pass 2 of 250System.out.println("\nRandom passwords:");51for (int i1 = 0; i < 2; i++) {52 String pwd = randomPassword(rand⟨Random A⟩, 8);53 System.out.println(" " + pwd);chars ← ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*
pass 2 of 2107}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++) {return sb.toString();
113 }114 return sb.toString();115}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:for (int i = 0; i < 2; i++)
pass 1 of 257System.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);hex ← 0123456789abcdef, sb ← (empty)
pass 1 of 7115}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 pass lengthhexsb1 8 0123456789abcdef (empty) 2 8 0123456789abcdef (empty) 3 8 0123456789abcdef (empty) 4 4 0123456789abcdef (empty) 5 4 0123456789abcdef (empty) 6 4 0123456789abcdef (empty) 7 12 0123456789abcdef (empty) for (int i = 0; i < length; i++)
pass 1 of 48118StringBuilder 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 pass ilength1 0 8 2 1 8 3 2 8 4 3 8 5 4 8 6 5 8 7 6 8 8 7 8 9 0 8 ⋯ 37 more passes ⋯ 47 10 12 48 11 12 return sb.toString();
121 }122 return sb.toString();123}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 53d06cf1for (int i = 0; i < 2; i++)
pass 2 of 257System.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);return sb.toString();
121 }122 return sb.toString();123}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: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);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}return sb.toString();
121 }122 return sb.toString();123}return sb.toString();
121 }122 return sb.toString();123}return sb.toString();
121 }122 return sb.toString();123}return sb.toString();
121 }122 return sb.toString();123}return sb.toString();
121 }122 return sb.toString();123}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:for (int i = 0; i < 2; i++)
pass 1 of 271System.out.println("\nRandom emails:");72for (int i0 = 0; i < 2; i++) {73 String email = randomEmail(rand⟨Random A⟩);74 System.out.println(" " + email);public static String randomEmail(Random rand)
pass 1 of 2132}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"};sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}return sb.toString();
97 }98 return sb.toString();99}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}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.comfor (int i = 0; i < 2; i++)
pass 2 of 271System.out.println("\nRandom emails:");72for (int i1 = 0; i < 2; i++) {73 String email = randomEmail(rand⟨Random A⟩);74 System.out.println(" " + email);public static String randomEmail(Random rand)
pass 2 of 2132}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"};sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}sb.append(randomLetter(rand));
95for (int i = 0; i < length; i++) {96 sb.append(randomLetter(rand⟨Random A⟩));97}return sb.toString();
97 }98 return sb.toString();99}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}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:for (int i = 0; i < 2; i++)
pass 1 of 278System.out.println("\nRandom phone numbers:");79for (int i0 = 0; i < 2; i++) {80 String phone = randomPhone(rand⟨Random A⟩);81 System.out.println(" " + phone);area ← 206, exchange ← 395, number ← 606
pass 1 of 2138}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}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-0606for (int i = 0; i < 2; i++)
pass 2 of 278System.out.println("\nRandom phone numbers:");79for (int i1 = 0; i < 2; i++) {80 String phone = randomPhone(rand⟨Random A⟩);81 System.out.println(" " + phone);area ← 679, exchange ← 846, number ← 1228
pass 2 of 2138}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}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
}
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]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--) {j ← 0, temp ← 5, arr[i] ← 1, arr[j] ← 5
pass 1 of 488public 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 pass irandjtemparr[i]arr[j]1 4 — 0 5 5 → 1 1 → 5 2 3 — 3 4 4 4 3 2 — 2 3 3 3 4 1 ⟨Random A⟩ 1 2 2 2 for (int i = 0; i < 4; i++)
pass 1 of 442String[] 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 pass i1 0 2 1 3 2 4 3 public static <T> T randomChoice(T[] arr, Random rand)
pass 1 of 495}96public static <T> T randomChoice(T[] arr, Random rand⟨Random A⟩) {97 return arr[rand.nextInt(arr.length5)];98}color ← Purple
43for (int i = 0; i < 4; i++) {44 String color→ Purple = randomChoice(colors, rand⟨Random A⟩);45 System.out.print(colorPurple + " ");46}outputPurplecolor ← Yellow
43for (int i = 0; i < 4; i++) {44 String color→ Yellow = randomChoice(colors, rand⟨Random A⟩);45 System.out.print(colorYellow + " ");46}outputYellowcolor ← Blue
43for (int i = 0; i < 4; i++) {44 String color→ Blue = randomChoice(colors, rand⟨Random A⟩);45 System.out.print(colorBlue + " ");46}outputBluecolor ← 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):copy ← [1, 2, 3, 4, 5]
pass 1 of 398}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 pass copy1 [1, 2, 3, 4, 5] 2 [1, 2, 3, 4, 5] 3 [1, 2, 3, 4, 5] 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:for (int i = 0; i < 2; i++)
pass 1 of 256System.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);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]for (int i = 0; i < 2; i++)
pass 2 of 256System.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);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:for (int i = 0; i < choices; i++)
pass 1 of 868int 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 pass i1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 total ← 0.0
pass 1 of 8103}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 pass total1 0.0 2 0.0 3 0.0 4 0.0 5 0.0 6 0.0 7 0.0 8 0.0 total ← 0.5
pass 1 of 32105double total = 0;106for (double w0.5 : weights) total→ 0.5 += w;32 passes — pass 1 is the card above pass wtotal1 0.5 0.0 → 0.5 2 0.3 0.5 → 0.8 3 0.15 0.8 → 0.9500000000000001 4 0.05 0.9500000000000001 → 1.0 5 0.5 0.0 → 0.5 6 0.3 0.5 → 0.8 7 0.15 0.8 → 0.9500000000000001 8 0.05 0.9500000000000001 → 1.0 9 0.5 0.0 → 0.5 ⋯ 21 more passes ⋯ 31 0.15 0.8 → 0.9500000000000001 32 0.05 0.9500000000000001 → 1.0 r ← 0.7499061812554475, cumulative ← 0.0
108double r→ 0.7499061812554475 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;cumulative ← 0.5
pass 1 of 13111for (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 pass iweights[i]cumulative1 0 0.5 0.0 → 0.5 2 1 0.3 0.5 → 0.8 3 0 0.5 0.0 → 0.5 4 0 0.5 0.0 → 0.5 5 0 0.5 0.0 → 0.5 6 1 0.3 0.5 → 0.8 7 0 0.5 0.0 → 0.5 8 0 0.5 0.0 → 0.5 9 1 0.3 0.5 → 0.8 ⋯ 2 more passes ⋯ 12 0 0.5 0.0 → 0.5 13 1 0.3 0.5 → 0.8 if (r < cumulative)
pass 1 of 8112cumulative += weights[i];113if (r0.7499061812554475 < cumulative0.8) {114 return i1;115}All 8 passes — pass 1 is the card above pass rcumulativei1 0.7499061812554475 0.8 1 2 0.38656687435934867 0.5 0 3 0.17737847790937833 0.5 0 4 0.5943499108896841 0.8 1 5 0.20976756886633208 0.5 0 6 0.825965871887821 0.9500000000000001 2 7 0.17221793768785243 0.5 0 8 0.5874273817862956 0.8 1 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}r ← 0.38656687435934867, cumulative ← 0.0
108double r→ 0.38656687435934867 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;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}r ← 0.17737847790937833, cumulative ← 0.0
108double r→ 0.17737847790937833 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;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}r ← 0.5943499108896841, cumulative ← 0.0
108double r→ 0.5943499108896841 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;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}r ← 0.20976756886633208, cumulative ← 0.0
108double r→ 0.20976756886633208 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;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}r ← 0.825965871887821, cumulative ← 0.0
108double r→ 0.825965871887821 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;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}r ← 0.17221793768785243, cumulative ← 0.0
108double r→ 0.17221793768785243 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;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}r ← 0.5874273817862956, cumulative ← 0.0
108double r→ 0.5874273817862956 = rand.nextDouble() * total1.0;109double cumulative→ 0.0 = 0;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}for (int i = 0; i < items.length; i++)
pass 1 of 474for (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 pass iitems[i]results[i]weights[i]1 0 Common 4 0.5 2 1 Uncommon 3 0.3 3 2 Rare 1 0.15 4 3 Epic 0 0.05 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:perm ← [A, B, C, D]
pass 1 of 281List<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]perm ← [A, B, C, D]
pass 2 of 281List<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