AP COMPUTER SCIENCE PRINCIPLES • ALGORITHMS AND PROGRAMMING

Random Values

How programs use randomness to model uncertainty, create variety, and simulate real-world unpredictability.

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
Stanislaw Ulam and John von Neumann develop the Monte Carlo method at Los Alamos, creating massive demand for machine-generated random numbers.
1949
Middle-Square Method
Von Neumann proposes the middle-square method — one of the earliest pseudorandom number generators (PRNGs) — acknowledging it is imperfect but computationally fast.
1955
RAND Corporation Table
RAND publishes "A Million Random Digits with 100,000 Normal Deviates," a book of hardware-generated random numbers used as a reference for decades.
1997
Mersenne Twister
Makoto Matsumoto and Takuji Nishimura publish the Mersenne Twister PRNG, which becomes the default generator in many programming languages including Python.
2016
AP CSP Exam Launches
The College Board introduces AP Computer Science Principles, which includes RANDOM as a built-in procedure in its pseudocode reference sheet.

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.

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.

1

RANDOM(a, b)

The AP CSP pseudocode procedure RANDOM(a, b) returns a random integer from a to b, inclusive. Each integer in the range is equally likely to be returned.
2

Uniform Distribution

Every value in the specified range has the same probability of being selected. For RANDOM(1, 6), each outcome (1 through 6) has a probability of 1/6.
3

Non-Determinism

A program that uses RANDOM may produce different outputs each time it runs, even with the same inputs. This contrasts with deterministic programs, which always produce identical results.
4

Pseudorandomness

Most programming languages use algorithms (PRNGs) that produce sequences that appear random but are generated deterministically from a seed value. For AP CSP purposes, treat RANDOM as truly random.
5

Range & Inclusivity

The AP pseudocode convention is inclusive on both ends: RANDOM(1, 10) can return 1, 2, 3, …, 10. This differs from some real languages where the upper bound is exclusive.
KEY TAKEAWAY
KEY TAKEAWAY

Visual Explanation

A histogram of 6000 simulated calls to 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.

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
RANDOM(a, b)
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
count = b − a + 1
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
P(n) = 1 / (b − a + 1)
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.

COMMON EXAM TRAP

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.

A tree diagram showing the four major categories of random value applications tested on AP CSP, with a code example of a coin-flip simulation. The pseudocode uses 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.

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.

1
Step 1 — Model the probabilityA 30% chance means 30 out of 100 outcomes should count as rain. We can use RANDOM(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 if RANDOM(1, 10) ≤ 3
2
Step 2 — Initialize variablesSet rainyDays ← 0 to count rain days, and day ← 1 to track the loop iteration.
rainyDays = 0, day = 1
3
Step 3 — Write the loopREPEAT 10 TIMES — inside the loop, generate roll ← RANDOM(1, 10). If roll ≤ 3, increment rainyDays by 1.
Each iteration: 30% chance of rain
4
Step 4 — Trace a possible executionSuppose 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 resultsBecause 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

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.

Comparison of deterministic vs. non-deterministic programs
PropertyDeterministic ProgramNon-Deterministic Program (uses RANDOM)
Same output every run?Yes — identical inputs always produce identical outputsNo — output can differ between runs with the same inputs
TestabilityEasy to test: run once, check outputHarder: must run many times and check the range/distribution of outputs
Use casesCalculations, sorting, searching, data processingSimulations, games, sampling, cryptography
DebuggingBugs are reproducibleBugs may appear intermittently due to specific random values
AP pseudocode indicatorNo RANDOM calls in the codeContains at least one call to RANDOM(a, b)
KEY TAKEAWAY
KEY TAKEAWAY

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.

AP CSP random values vs. advanced computer science
FeatureAP CSP LevelAdvanced / College CS
Distribution typeUniform integers onlyGaussian, exponential, Poisson, custom distributions
Source of randomnessTreated as truly randomPRNGs (algorithmic) vs. TRNGs (hardware entropy)
Seed controlNot discussedSeeds allow reproducible "random" sequences for debugging
Security considerationsNot assessedCryptographically secure PRNGs (CSPRNGs) required for keys and tokens
Statistical analysisInformal: "each value equally likely"Chi-square tests, autocorrelation, spectral analysis of sequences

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.

Practice Problems

1
A program contains the statement x ← RANDOM(1, 5). Which of the following best describes the behavior of this program?
2
Consider the expression result ← RANDOM(3, 8) + 10. What is the complete range of possible values for result?
3
A program executes the following code: 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.
PROBLEM 4APPLIED
A teacher wants to write a program that randomly assigns each of 30 students to one of three groups: Red, Green, or Blue, with each group being equally likely. The students' names are stored in a list called students (indices 1 through 30). Write AP pseudocode that iterates through the list and displays each student's name followed by their assigned group.
PROBLEM 5CRITICAL THINKING
A student writes the following program to simulate rolling two dice and checking whether the sum is 7: 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.
Varsity Tutors • AP Computer Science Principles • Random Values