Core Concepts | .9 | .11 | .12 | .13 | .14 | .15 | .16 | .17 | .18 |
3.15 Random Values
A supplemental blog on random values. Learn how random values are often used in simulations, games, etc.
Random Values
Introduction
Random values are widely used in programming for various applications such as simulations, games, security, and testing. Randomness introduces variability and helps create unpredictable outcomes.
Objectives
By the end of this lesson, students will be able to:
- Understand what random values are.
- Write pseudocode using random value generation.
- Apply random values in practical scenarios.
Key Concepts
Random Values
: Values generated in such a way that each value within a specified range has an equal chance of being selected.Random Number Generators (RNGs)
: Algorithms or functions that produce random values.
Example Syntax (College Board Pseudo code)
College Board pseudocode uses the following structure for generating random values:
RANDOM(a, b)
Where a and b are the lower and upper bounds of the range (inclusive).
<span style="color:blue">Example 1: Rolling a Die</span>
Pseudocode
Let's write pseudocode to simulate rolling a six-sided die:
result ← RANDOM(1, 6)
DISPLAY result
<span style="color:blue">Example 2: Random Decision Making</span>
Pseudocode
Let's consider a scenario where we make a random decision between "yes" and "no":
decision ← RANDOM(1, 2)
IF decision = 1
{
DISPLAY "Yes"
}
ELSE
{
DISPLAY "No"
}
## Python
Here is the equivalent Python code:
```python
import random
decision = random.randint(1, 2)
if decision == 1:
print("Yes")
else:
print("No")
No
Example 3: Write pseudocode to simulate drawing a random card from a standard deck of 52 cards:
Generate a random number between 1 and 52. Display the card number. card ← RANDOM(1, 52) DISPLAY “Card number: “ + card
Python
Here is the equivalent Python code:
import random
card = random.randint(1, 52)
print("Card number:", card)
Card number: 52
Summary Random values introduce variability and unpredictability into programs, making them essential for various applications. By understanding how to generate and use random values, you can enhance your programs with elements of randomness.
Hacks
Review each of the sections above and produce …
- Write pseudocode to simulate flipping a coin 10 times and display the result of each flip.
- Write a python segment to generate a random password of 8 characters, using uppercase letters, lowercase letters, and digits.