AP CSP topic 3.15
Random Values
Programs can generate random numbers to add chance, like rolling dice or shuffling cards. In AP pseudocode, RANDOM(a, b) returns a whole number from a to b, including both ends, and each value is equally likely. Because results change each run, you test random programs by checking the range of possible outputs rather than one exact answer.
Random Values vocabulary
- RANDOM(a, b): Returns a random integer from a to b, inclusive.
- Inclusive: Includes the end values; RANDOM(1, 6) can return 1 or 6.
- Probability: How likely an outcome is, from 0 (never) to 1 (always).
- Nondeterministic: Able to give different outputs from the same input on different runs.
AP-style practice questions
Try each one, then open the answer. To save your progress, take this quiz in the interactive course.
1. Which of the following values can RANDOM(3, 7) return?
- (A) Only 3 or 7
- (B) Any whole number from 3 to 7, including 3 and 7
- (C) Any whole number from 4 to 6
- (D) Any decimal number between 3 and 7
Show answer
(B) Any whole number from 3 to 7, including 3 and 7 RANDOM(a, b) returns an integer from a to b, inclusive.
2. A game should simulate flipping a fair coin. Which code makes "Heads" and "Tails" equally likely?
- (A) IF (RANDOM(1, 2) = 1) { DISPLAY("Heads") } ELSE { DISPLAY("Tails") }
- (B) IF (RANDOM(1, 3) = 1) { DISPLAY("Heads") } ELSE { DISPLAY("Tails") }
- (C) DISPLAY("Heads")
- (D) IF (RANDOM(1, 10) > 2) { DISPLAY("Heads") } ELSE { DISPLAY("Tails") }
Show answer
(A) IF (RANDOM(1, 2) = 1) { DISPLAY("Heads") } ELSE { DISPLAY("Tails") } RANDOM(1, 2) gives 1 or 2 with equal chance.
x ← RANDOM(1, 4) y ← RANDOM(1, 4) DISPLAY(x + y)
3. Which of the following could NOT be displayed?
- (A) 2
- (B) 5
- (C) 8
- (D) 9
Show answer
(D) 9 The largest possible sum is 4 + 4 = 8.
4. Which of the following is the probability that RANDOM(1, 10) returns a number less than 4?
- (A) 3/10
- (B) 4/10
- (C) 1/2
- (D) 1/4
Show answer
(A) 3/10 Three of the ten equally likely values (1, 2, 3) are less than 4.