SECTION 1
Historical Context & Motivation
Long before digital computers existed, people relied on physical devices — dice, shuffled cards, and coin flips — to inject unpredictability into games, lotteries, and scientific experiments. The challenge of producing random values mechanically became urgent during World War II, when researchers at Los Alamos needed millions of random numbers for Monte Carlo simulations to model neutron diffusion in nuclear weapons. Manual methods were far too slow, so mathematicians like John von Neumann devised the first algorithmic approaches to generating sequences that appeared random, even though they were entirely determined by a starting value.
1946 • Monte Carlo Method
1949 • Middle-Square Method
1955 • RAND Corporation Table
1997 • Mersenne Twister
2016 • AP CSP Exam Launches
The central question this lesson addresses is straightforward yet profound: how can a deterministic machine — one that follows precise instructions — produce values that behave as though they are random? Understanding this question, and the AP CSP exam's conventions for random number generation, is essential for writing programs that simulate, model, and create variety.
SECTION 2
Core Principles & Definitions
At the AP CSP level, you need to understand what random values are, how the exam's pseudocode generates them, and why randomness introduces fundamentally different behavior compared to deterministic programs. The following core ideas form the foundation of this topic.
RANDOM(a, b)
RANDOM(a, b) returns a random integer from a to b, inclusive. Each integer in the range is equally likely to be returned.Uniform Distribution
RANDOM(1, 6), each outcome (1 through 6) has a probability of 1/6.Non-Determinism
Pseudorandomness
Range & Inclusivity
RANDOM(1, 10) can return 1, 2, 3, …, 10. This differs from some real languages where the upper bound is exclusive.SECTION 3
Visual Explanation
RANDOM(1, 6). Each bar represents the frequency of one outcome. The dashed pink line marks the expected frequency of 1000 (6000 ÷ 6). Notice that the bars are approximately equal but not identical — this natural variation is characteristic of randomness.The diagram above illustrates a fundamental property of uniform random distributions: over many trials, each possible outcome occurs with roughly the same frequency, but any single call is unpredictable. The slight variation from bar to bar is not a flaw — it is a hallmark of genuine randomness. If every bar were exactly 1000, the sequence would actually be suspiciously non-random, because perfect uniformity in a finite sample is exceedingly unlikely. As the number of trials grows, the relative differences shrink, converging toward the theoretical probability of 1/6 per outcome.
SECTION 4
How RANDOM Works in AP Pseudocode
The AP CSP reference sheet defines a single randomness procedure. Understanding its exact semantics — the range, the data type, and how it interacts with variables and expressions — is essential for answering exam questions correctly.
AP PSEUDOCODE SYNTAX
Returns a random integer n such that a ≤ n ≤ b. Both endpoints are inclusive. Each integer in [a, b] is equally likely.
NUMBER OF POSSIBLE VALUES
For RANDOM(1, 10), the count is 10 − 1 + 1 = 10 possible values. For RANDOM(3, 7), the count is 7 − 3 + 1 = 5.
PROBABILITY OF ANY SINGLE OUTCOME
Under a uniform distribution, every integer in the range has the same probability. For RANDOM(1, 4), each value has P = 1/4 = 0.25 = 25%.
Using RANDOM in Expressions
Because RANDOM(a, b) returns an integer, you can embed it in any arithmetic expression. For example, score ← score + RANDOM(1, 6) adds a random value between 1 and 6 to the variable score. The expression RANDOM(0, 1) returns either 0 or 1, which is useful for simulating a fair coin flip. A common exam pattern uses modular arithmetic or conditionals on the random result to map values into categories — for example, assigning "heads" when RANDOM(1, 2) = 1 and "tails" otherwise.
SECTION 5
Applications & Patterns
Random values appear in a wide range of programming contexts. The AP exam expects you to recognize common patterns and trace code that uses RANDOM within loops, conditionals, and list operations. Below is a classification of the most frequently tested applications.
RANDOM(1, 2) to model a fair coin, counting the number of heads across 100 trials.Random Selection from a List
A particularly important pattern on the AP exam involves using RANDOM to select an element from a list. If a list colors contains 5 elements indexed 1 through 5, the expression colors[RANDOM(1, LENGTH(colors))] picks a random element. Note that AP pseudocode lists are 1-indexed, so the valid range starts at 1, not 0. This is a frequent source of off-by-one errors on the exam.
SECTION 6
Worked Example: Simulating a Weighted Event
Suppose you want to simulate a weather model where there is a 30% chance of rain on any given day. The program should simulate 10 days and count how many are rainy. Let's trace through the logic step by step.
Worked example
- 1
Step 1 — Model the probability
A 30% chance means 30 out of 100 outcomes should count as rain. We can useRANDOM(1, 100)and define rain as any result ≤ 30. Alternatively,RANDOM(1, 10)with rain for results ≤ 3 works just as well, since 3/10 = 30%.Rain ifRANDOM(1, 10) ≤ 3 - 2
Step 2 — Initialize variables
SetrainyDays ← 0to count rain days, andday ← 1to track the loop iteration.rainyDays = 0, day = 1 - 3
Step 3 — Write the loop
REPEAT 10 TIMES— inside the loop, generateroll ← RANDOM(1, 10). Ifroll ≤ 3, incrementrainyDaysby 1.Each iteration: 30% chance of rain - 4
Step 4 — Trace a possible execution
Suppose the 10 calls to RANDOM produce: 7, 2, 5, 1, 9, 4, 3, 8, 6, 10. Values ≤ 3 are: 2, 1, 3 — that is 3 rainy days. Another run might produce different random values, yielding 1, 4, or 5 rainy days.rainyDays = 3 (this run) - 5
Step 5 — Interpret results
Because the program uses RANDOM, the output is non-deterministic: it will differ between runs. Over many runs, the average number of rainy days should approach 3 (30% of 10), but any single run can deviate. The expected value is 10 × 0.30 = 3.0.Expected rainy days = 10 × 0.30 = 3.0
SECTION 7
Deterministic vs. Non-Deterministic Programs
The distinction between deterministic and non-deterministic behavior is one of the most important conceptual divides in AP CSP. Programs that do not use RANDOM (or external input that varies) produce the same output every time they run. Programs that incorporate random values break this guarantee.
| Property | Deterministic Program | Non-Deterministic Program (uses RANDOM) |
|---|---|---|
| Same output every run? | Yes — identical inputs always produce identical outputs | No — output can differ between runs with the same inputs |
| Testability | Easy to test: run once, check output | Harder: must run many times and check the range/distribution of outputs |
| Use cases | Calculations, sorting, searching, data processing | Simulations, games, sampling, cryptography |
| Debugging | Bugs are reproducible | Bugs may appear intermittently due to specific random values |
| AP pseudocode indicator | No RANDOM calls in the code | Contains at least one call to RANDOM(a, b) |
Comparison of deterministic vs. non-deterministic programs
SECTION 8
Connection to Advanced Topics
The AP CSP treatment of randomness is intentionally simplified. In more advanced computer science courses and real-world applications, the topic branches into sophisticated territory. Understanding where RANDOM(a, b) sits in this broader landscape can deepen your conceptual understanding and prepare you for college-level study.
| Feature | AP CSP Level | Advanced / College CS |
|---|---|---|
| Distribution type | Uniform integers only | Gaussian, exponential, Poisson, custom distributions |
| Source of randomness | Treated as truly random | PRNGs (algorithmic) vs. TRNGs (hardware entropy) |
| Seed control | Not discussed | Seeds allow reproducible "random" sequences for debugging |
| Security considerations | Not assessed | Cryptographically secure PRNGs (CSPRNGs) required for keys and tokens |
| Statistical analysis | Informal: "each value equally likely" | Chi-square tests, autocorrelation, spectral analysis of sequences |
AP CSP random values vs. advanced computer science
In machine learning, randomness plays a critical role in weight initialization, data shuffling, and stochastic gradient descent. In cybersecurity, weak random number generators have been the root cause of catastrophic vulnerabilities — the 2012 discovery that thousands of RSA keys shared prime factors due to poor PRNG seeding affected real-world encryption. While these topics are beyond AP CSP, they illustrate why understanding randomness matters far beyond the exam.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
x ← RANDOM(1, 5). Which of the following best describes the behavior of this program?- A. The variable x will always be assigned the value 3, the midpoint of 1 and 5.
- B. The variable x will be assigned a random value from the set {1, 2, 3, 4, 5}, and the value may differ each time the program runs.
- C. The variable x will be assigned a random decimal between 1.0 and 5.0.
- D. The variable x will be assigned a random value from the set {1, 2, 3, 4}, because the upper bound is exclusive.
Show answer (B)
Question 2: BASIC CALCULATION
result ← RANDOM(3, 8) + 10. What is the complete range of possible values for result?- A. 3 to 8
- B. 10 to 18
- C. 13 to 18
- D. 13 to 17
Show answer (C)
Question 3: INTERMEDIATE
num ← RANDOM(1, 4)
IF (num = 1)
DISPLAY("A")
ELSE
IF (num ≤ 3)
DISPLAY("B")
ELSE
DISPLAY("C")
Select two true statements about this program.- A. The program has a 25% chance of displaying "A".
- B. The program has a 50% chance of displaying "B".
- C. The program has a 50% chance of displaying "C".
- D. The program always displays the same output each time it runs.
Show answer (A,B)
Question 4: APPLIED
students (indices 1 through 30). Write AP pseudocode that iterates through the list and displays each student's name followed by their assigned group.Show answer
FOR EACH student IN students
{
group ← RANDOM(1, 3)
IF (group = 1)
DISPLAY(student + " Red")
ELSE IF (group = 2)
DISPLAY(student + " Green")
ELSE
DISPLAY(student + " Blue")
}
Rubric: (1 point) Loop iterates through all students. (1 point) RANDOM(1, 3) generates an equally likely value for three groups. (1 point) Conditional logic correctly maps 1 → Red, 2 → Green, 3 → Blue. (1 point, bonus) DISPLAY outputs both the student name and assigned group. An alternative valid approach uses a list of group names and indexes into it with the random value.Question 5: CRITICAL THINKING
die ← RANDOM(1, 6)
sum ← die + die
IF (sum = 7)
DISPLAY("You win!")
ELSE
DISPLAY("Try again")
(a) Explain the logical error in this program.
(b) Describe why the error makes it impossible for the program to ever display "You win!".
(c) Write corrected pseudocode that fixes the error.
(d) In the corrected version, what is the probability that the program displays "You win!"? Justify your answer.Show answer
die. The expression die + die doubles that single value rather than adding two independent rolls.
(b) Since sum = 2 × die, the possible sums are {2, 4, 6, 8, 10, 12} — all even numbers. Because 7 is odd, the condition sum = 7 can never be true, so "You win!" is never displayed.
(c) Corrected code:
die1 ← RANDOM(1, 6)
die2 ← RANDOM(1, 6)
sum ← die1 + die2
IF (sum = 7)
DISPLAY("You win!")
ELSE
DISPLAY("Try again")
(d) With two independent dice, there are 6 × 6 = 36 equally likely outcomes. The pairs that sum to 7 are (1,6), (2,5), (3,4), (4,3), (5,2), (6,1) — six combinations. Therefore P(sum = 7) = 6/36 = 1/6 ≈ 16.7%.