Skip to the content.

Random Algorithms and Simulation Games - Gyutae KIm

Popcorn Hack #1: Brainstorm

What is a random algorithm? A random algorithm uses randomness or probabilistic behavior to solve problems, often relying on random number generation.

Why use random algorithms in real-life coding? They are useful for simulations, cryptography, gaming, and optimization problems where unpredictability or approximation is needed.

What questions might College Board ask?

Define random algorithms and give examples. Explain their real-world applications. Compare random and deterministic algorithms.

Popcorn HAck 2

import random

# Step 1: Define a list of activities
activities = [
    'Play a board game', 
    'Go hiking', 
    'Bake cookies', 
    'Learn a new programming language', 
    'Do yoga', 
    'Paint or draw', 
    'Organize your room', 
    'Watch a documentary', 
    'Try a new workout', 
    'Write a short story', 
    'Plan your next vacation'
]

# Step 2: Randomly choose an activity
random_activity = random.choice(activities)

# Step 3: Display the chosen activity
print(f"Today’s random activity: {random_activity}")
Today’s random activity: Try a new workout

Popcorn Hack 3

import random
# Step 1: Define the list of hosts and activities
hosts = ['Rayhaan','Gyutae','Derek']
activities = ['music', 'food', 'decorations', 'games', 'movies']
# Step 2: Randomly shuffle the list of activities
random.shuffle(activities)
# Step 3: Loop through each host and assign them a random activity
for i in range(len(hosts)):
    print(f"{hosts[i]} will be monitoring {activities[i]}!")
Rayhaan will be monitoring music!
Gyutae will be monitoring food!
Derek will be monitoring games!

MCQ

Analyzing Code Segments RNG

Answer: C 3 isn’t a possible choice for the first iteration pick is only going to be from 1 to 2 on the first time since i is 2 Science experiment with 75 percent successful trials In a certain science experiment, 75 percent of trials are expected to be successful and 25 percent of trials are expected to be unsuccessful. The program below is intended to simulate the results of repeated trials of the experiment.

successful ← 0 unsuccessful ← 0 REPEAT 1000 TIMES { IF () { successful ← successful + 1 } ELSE { unsuccessful ← unsuccessful + 1 } } DISPLAY(successful) DISPLAY("trials were successful,") DISPLAY(unsuccessful) DISPLAY("trials were unsuccessful.") Which of the following can be used to replace < MISSING CODE > so that the simulation works as intended? A: RANDOM, open parenthesis 1 comma 100, close parenthesis, equals 25 B: RANDOM, open parenthesis 1 comma 100, close parenthesis, is less than or equal to 25 C: RANDOM, open parenthesis 1 comma 100, close parenthesis, equals 75 D: RANDOM, open parenthesis 1 comma 100, close parenthesis, is less than or equal to 75

Answer: D This option causes the experiment to be successful when RANDOM, open parenthesis 1 comma 100, close parenthesis produces a result from 1 to 75, or 75% of the time.

Random Algorithms

Popcorn HAck 1

# Number Spinner Simulation
import random

# Define the range of numbers for the spinner
spinner_range = list(range(1, 21))  # Spinner with numbers from 1 to 20

# Randomly select a number from the spinner
spun_number = random.choice(spinner_range)

# Display the result
print(f"The spinner landed on: {spun_number}")
The spinner landed on: 15

Popcorn Hack 2

import random

def play_rock_paper_scissors():
    choices = ['rock', 'paper', 'scissors']
    computer_choice = random.choice(choices)
    user_choice = input("Enter your choice (rock, paper, or scissors): ")

    if user_choice not in choices:
        print("Invalid choice. Please try again.")
        return

    print("Computer chose:", computer_choice)
    print("You chose:", user_choice)

    if user_choice == computer_choice:
        print("It's a tie!")
    elif (user_choice == 'rock' and computer_choice == 'scissors') or (user_choice == 'paper' and computer_choice == 'rock') or (user_choice == 'scissors' and computer_choice == 'paper'):
        print("You win!")
    else:
        print("You lose!")

play_rock_paper_scissors()
Computer chose: scissors
You chose: rock
You win!

MCQ

Which of the following strategies is LEAST likely to provide a more accurate prediction? A: Gathering data for additional years to try to identify patterns in birth rates B: Refining the model used in the computer simulation to more closely reflect the data from the past ten years C: Removing as many details from the model as possible so that calculations can be performed quickly D: Taking into consideration more information about the community, such as the ages of residents

Answer: C Removing details from the model may help it run quickly, but is unlikely to provide more accurate results. Mouse and Predator Simulations A researcher wrote a program to simulate the number of mice in an environment that contains predators. The program uses the following procedures.

Procedure Call Explanation InitialMousePopulation() Returns the number of mice at the start of the simulation InitialPredatorPopulation() Returns the number of predators at the start of the simulation NextDayPopulation(numberOfMice, numberOfPredators) Based on the current numbers of mice and predators, returns the number of mice after one day Code for the simulation is shown below. days ← 0 numMice ← InitialMousePopulation() numPredators ← InitialPredatorPopulation() REPEAT UNTIL (days = 365) { numMice ← NextDayPopulation(numMice, numPredators) days ← days + 1 } DISPLAY(“There are”) DISPLAY(numMice) DISPLAY(“mice after one year.”) Based on the code, which of the following assumptions is made in the simulation? A: The number of mice increases by 1 each day. B: The number of mice does not change from day to day. C: The number of predators increases by 1 each day. D: The number of predators does not change from day to day.

Answer: D The number of predators is initialized at the beginning of the program but is never updated.

HW Hack 1

import random

# Step 1: Define the list of students and team names
students = [
    "Alice", "Bob", "Charlie", "Diana", "Eve", 
    "Frank", "Grace", "Hank", "Ivy", "Jack", 
    "Karen", "Leo", "Mona", "Nina", "Oscar"
]
teams = ["Team Phoenix", "Team Dragon", "Team Griffin"]

# Step 2: Create a dictionary to store team assignments
team_assignments = {team: [] for team in teams}

# Step 3: Randomly assign each student to a team
for student in students:
    assigned_team = random.choice(teams)
    team_assignments[assigned_team].append(student)

# Step 4: Print out the list of students and their assigned teams
for team, members in team_assignments.items():
    print(f"{team}: {', '.join(members)}")
Team Phoenix: Alice, Grace, Hank, Leo, Nina
Team Dragon: Charlie, Eve, Ivy, Jack, Mona, Oscar
Team Griffin: Bob, Diana, Frank, Karen

HW hack 2

import random

# Step 1: Define the possible weather types
weather_types = ["Sunny", "Cloudy", "Rainy"]

# Step 2: Generate random weather for 7 days
forecast = [random.choice(weather_types) for _ in range(7)]

# Step 3: Print the weather for each day
print("7-Day Weather Forecast:")
for day, weather in enumerate(forecast, start=1):
    print(f"Day {day}: {weather}")
7-Day Weather Forecast:
Day 1: Rainy
Day 2: Cloudy
Day 3: Sunny
Day 4: Sunny
Day 5: Sunny
Day 6: Sunny
Day 7: Cloudy

HW HAck 3

import random

# Step 1: Define the number of customers and their random service times
customers = ["Customer 1", "Customer 2", "Customer 3", "Customer 4", "Customer 5"]
service_times = [random.randint(1, 5) for _ in customers]

# Step 2: Simulate serving customers and calculate total time
total_time = 0
print("Coffee Shop Queue Simulation:")
for i, customer in enumerate(customers):
    service_time = service_times[i]
    total_time += service_time
    print(f"{customer} is being served. Service time: {service_time} minutes.")

# Step 3: Print the total time for all customers to be served
print(f"\nTotal time to serve all customers: {total_time} minutes.")
Coffee Shop Queue Simulation:
Customer 1 is being served. Service time: 2 minutes.
Customer 2 is being served. Service time: 5 minutes.
Customer 3 is being served. Service time: 3 minutes.
Customer 4 is being served. Service time: 1 minutes.
Customer 5 is being served. Service time: 4 minutes.

Total time to serve all customers: 15 minutes.