1. Reference Guide

Key Vocabulary

Term Definition Example
Random value A value selected from a set/range according to a random process. A game where you are spinning a wheel → random value could be 250 coins
Inclusive range Both endpoints can be selected. A random integer from 1 through 4 can return 1 or 4
Possible output Any result the expression is allowed to produce. 1, 2, 3, or 4
Random choice Selects one item from an array. parts[Math.floor(Math.random() * parts.length)]
QA simulation Repeated test runs used to exercise different program paths. random record + random API action

JavaScript Random Quick Reference

const recordId = Math.floor(Math.random() * 4) + 1;
const part = parts[Math.floor(Math.random() * parts.length)];

Reasoning Rules

  • Math.random() returns a number from 0 (inclusive) to 1 (exclusive).
  • Math.floor(Math.random() * (max - min + 1)) + min creates an integer from min through max, inclusive.
  • A value can repeat on consecutive runs.
  • Seeing a few outputs does not prove those are the only possible outputs.
  • Choosing one array element keeps the chosen object intact.
  • Before using a random index/range, verify every generated value is valid.
  • For reproducible debugging, use a seeded random-number generator; JavaScript’s built-in Math.random() cannot be seeded directly.

2. LxD Cycle Process

Empathize: Random code can be confusing because students may expect every result to appear once before a repeat, forget whether endpoints are included, or use a range that can generate invalid values.

Define:

  • POV: CSP students need to reason about every possible random output before using randomness in a program, because testing only one run does not prove a random algorithm is correct.
  • Learning Goal: Students will generate random integers, select random list items, identify possible results, and use random values in a repeatable backend QA workflow.

Ideate:

  • HMW Question: How might we use randomness to test different SFI automotive records and backend actions without accidentally generating invalid choices?
  • HMW Question: How might we verify a random expression by reasoning about its full set of possible outputs?
  • Activity: Generate record IDs, choose structured part records, route random API actions, then build a reusable QA simulator.

Prototype & Test: Run each example multiple times, record the outputs you observe, then explain the complete set of outputs that are possible even if a particular value does not appear during your tests.


3. College Board Requirements

AP CSP Topic 3.15: Random Values asks students to write expressions that generate possible values and evaluate expressions to determine all possible results. The exam reference sheet uses RANDOM(a, b), which returns an integer from a to b, inclusive.

Connect the pseudocode to JavaScript:

College Board pseudocode JavaScript
RANDOM(1, 4) Math.floor(Math.random() * 4) + 1
possible outputs: 1,2,3,4 possible outputs: 1,2,3,4
each execution may differ repeated JavaScript runs may differ

JavaScript uses Math.random() with array indexes to choose one complete record from structured test data.

College Board Pseudocode

AP CSP uses RANDOM(a, b) in its pseudocode. It returns a random integer from a through b, inclusive.

Random Values: College Board vs JavaScript

College Board pseudocode JavaScript
RANDOM(1, 4) Math.floor(Math.random() * 4) + 1
list positions begin at 1 JavaScript array indexes begin at 0
LENGTH(parts) parts.length
parts[index] parts[index - 1] when using a 1-based pseudocode index

SFI QA Selection in College Board Pseudocode

recordIndex ← RANDOM(1, LENGTH(parts))
actionNumber ← RANDOM(1, 4)

selectedPart ← parts[recordIndex]

IF (actionNumber = 1)
{
    DISPLAY("GET/search")
}
ELSE
{
    IF (actionNumber = 2)
    {
        DISPLAY("POST/create")
    }
    ELSE
    {
        IF (actionNumber = 3)
        {
            DISPLAY("PUT/update")
        }
        ELSE
        {
            DISPLAY("DELETE/remove")
        }
    }
}

Possible Results

If LENGTH(parts) = 3:

  • recordIndex can be 1, 2, or 3.
  • actionNumber can be 1, 2, 3, or 4.
  • There are 3 × 4 = 12 possible record/action pairs.
  • A pair may repeat on consecutive runs.

JavaScript Equivalent

const selectedPart = parts[Math.floor(Math.random() * parts.length)];
const actions = [
    "GET/search",
    "POST/create",
    "PUT/update",
    "DELETE/remove"
];
const selectedAction = actions[Math.floor(Math.random() * actions.length)];

Pseudocode Check

Before running your simulator, choose one possible recordIndex and actionNumber, trace the pseudocode by hand, and predict the displayed action. Then compare that reasoning with your JavaScript implementation.


4. Lesson Plan

Learning Objective: Generate random values in JavaScript, determine every possible result, and apply randomness to backend-style testing.

Success Criteria: You can choose a valid random range, explain whether endpoints are included, distinguish random choice from guaranteed rotation, and use random results safely in program logic.

Lesson Theme — SFI Backend QA Test Garage

Theme: You are a QA engineer stress-testing an SFI automotive safety-spec backend.

The lesson keeps one story from start to finish:

  • Records: SFI automotive components.
  • Random record selection: chooses which part gets tested.
  • Random API action: chooses search, create, update, or remove behavior.
  • Existing spec numbers: create realistic duplicate conditions.
  • Repeated runs: exercise different backend paths.

Randomness is not added just for entertainment. It represents a real testing strategy:

“Can the backend handle many valid combinations of records and actions without producing an invalid state?”

The final simulator combines the full theme into repeated QA runs.

Teaching rhythm

Pause for each Popcorn Hack during the lesson: give students about two minutes to predict, edit and run the nearby code, then ask a partner to explain the result before continuing. Students copy their work and visible output into their own notebook after the live check. Save the independent Homework Hack for after class.

Tech Talk (short segments between checks)

JavaScript’s Math.random() generates a decimal from 0 (inclusive) to 1 (exclusive). Scale and round it to create integers or choose array elements:

JavaScript Purpose Example
Math.floor(Math.random() * (max - min + 1)) + min Random integer from min through max, inclusive Math.floor(Math.random() * 4) + 1
items[Math.floor(Math.random() * items.length)] Random item from an array parts[Math.floor(Math.random() * parts.length)]
repeated calls Independent random selections the same result may repeat

A random result is not the same as cycling through all values. Repeats are normal.


5. Code Examples

A. Simple: Random SFI Record ID

// CODE_RUNNER: Tech Talk 1 - Random SFI Record ID

const sfiRecordId = Math.floor(Math.random() * 4) + 1;
console.log("SFI record selected for QA:", sfiRecordId);

Popcorn Hack 1: Random SFI Record Number

A backend QA script has four SFI part records numbered 1 through 4. The selected record number should be random and every valid record should be reachable.

Your finished runner should produce valid record numbers and explain why repeated values are allowed.

In class (2 minutes): Predict the first output, complete the runner, run it, then change one input and compare with a partner. Save your code and output in your personal notebook.

// CODE_RUNNER: Popcorn Hack 1 - Random SFI Record Number

const recordCount = 4;

// Build and test your solution below.

B. Random Choice from an Array

Instead of choosing only an ID, select one complete SFI part name from an array.

// CODE_RUNNER: Tech Talk 2 - Random SFI Part

const sfiParts = [
    "Replacement Flywheels and Clutch Assemblies",
    "Multiple Disc Clutch Assemblies",
    "Racing Flywheel Record"
];

const selectedPart = sfiParts[Math.floor(Math.random() * sfiParts.length)];
console.log("SFI part selected for testing:", selectedPart);

Popcorn Hack 2: Random Structured SFI Car Part

The backend stores SFI automotive records as structured data with product name, category, and spec number.

Randomly select one complete record and display the selected record’s information without breaking the relationship between its fields.

In class (2 minutes): Decide what the first run should show, complete and run the code, then change one input to test the opposite case. Explain the result aloud and transfer both cases to your notebook.

// CODE_RUNNER: Popcorn Hack 2 - Random SFI Part Record

const parts = [
    {
        "product_name": "Replacement Flywheels and Clutch Assemblies",
        "category": "Auto Racing",
        "spec_number": "1.1"
    },
    {
        "product_name": "Multiple Disc Clutch Assemblies",
        "category": "Drag Racing",
        "spec_number": "1.2"
    },
    {
        "product_name": "Racing Flywheel Record",
        "category": "Auto Racing",
        "spec_number": "2.1"
    }
];

// Build and test your solution below.

C. Random Values Control Program Paths

A QA script can randomly choose a backend action, then route that choice through an if statement.

// CODE_RUNNER: Tech Talk 3 - Random SFI Backend Action

const actions = ["GET/search", "POST/create"];

const selectedAction = actions[Math.floor(Math.random() * actions.length)];

if (selectedAction === "GET/search") {
    console.log("QA test: search for an SFI part record");
} else {
    console.log("QA test: validate an SFI part before creating it");
}

Popcorn Hack 3: Random SFI API Test

A backend QA system should vary both the SFI part being tested and the API action being simulated.

Randomly choose a part and an action, then route each action through the appropriate backend-style response.

In class (3 minutes): Predict two possible action outcomes, complete and run the code, then change the query or action. Share why the result changed; preserve your tested work in your notebook.

// CODE_RUNNER: Popcorn Hack 3 - Random SFI API Test

const parts = [
    {"product_name": "Replacement Flywheels", "spec_number": "1.1"},
    {"product_name": "Multiple Disc Clutch Assemblies", "spec_number": "1.2"},
    {"product_name": "Racing Flywheel Record", "spec_number": "2.1"}
];

const actions = [
    "GET/search",
    "POST/create",
    "PUT/update"
];

// Build and test your solution below.

Prize Wheel Code Runner Challenges

Use these interactive challenges to apply random values to a simple game. Run each one, change the values, and explain what results are possible.

A. Spin the Prize Wheel

Code Runner Challenge

Change the prize amounts or add another prize, then run the code several times. Which prizes can the player win? Can a prize repeat?

// CODE_RUNNER: Change the prizes, spin the wheel, and explain the possible results

const prizes = [50, 100, 250, 500];
const prize = prizes[Math.floor(Math.random() * prizes.length)];

console.log("You won", prize, "coins!");

B. Generate a Random Coin Prize

Code Runner Challenge

Generate a random whole-number prize from minCoins through maxCoins, including both endpoints. Change the range and run it again. Explain how you know the endpoints are possible.

// CODE_RUNNER: Generate and test an inclusive random coin range

const minCoins = 100;
const maxCoins = 500;
const prize = Math.floor(Math.random() * (maxCoins - minCoins + 1)) + minCoins;

console.log("You won", prize, "coins!");

C. Checking a Player’s Coins

Code Runner Challenge

Change the player’s name or coin total and run the code. Try totals below, equal to, and above the upgrade cost. Predict which message will appear before each run.

// CODE_RUNNER: Change the player name or coin total and test the upgrade check

const playerName = "Alex";
const coins = 8;
const upgradeCost = 10;

if (coins >= upgradeCost) {
    console.log(playerName + " can buy a power-up!");
} else {
    console.log(playerName + " needs more coins.");
}

In-class MCQ Check

4 questions, one at a time. Answer each question, check it, then continue. At the end, copy the result line into your notebook and submission Notes.


6. Independent Homework & Submission

The three Popcorn Hacks above are live understanding checks. You are responsible for copying or preparing their code, predictions, and visible output in your personal notebook; the lesson page does not collect that work for you. Do the Homework Hack independently after the lesson.

Prepare your submission IPYNB

  1. In your portfolio, create a separate notebook under _notebooks/homework for this lesson. Keep the roughly four lesson notebooks expected for submission ready and individually identifiable; this lesson accounts for one notebook.
  2. Put this submission notebook frontmatter in a raw cell at the very top. It differs from the lesson page frontmatter above. Replace yourGithubID with your own ID:
---
layout: post
codemirror: true
title: 3.15 Random Values HW
categories: [JavaScript]
lesson_language: JavaScript
lesson_topic: Random-Values HW
lesson_part: interactive
lesson_type: lesson
permalink: /javascript/random-hw
author: yourGithubID
---
  1. Add your three in-class Popcorn Hacks with predictions and output, the MCQ result, then your independent Homework Hack and test output. Use headings to separate them. Run the notebook and publish your portfolio page.
  2. Submit the published homework notebook URL in the Link Submission form below. Put your MCQ result and brief test evidence in the Description field.

Suggested Notes:

Lesson: CSP 3.15 Random Values
Notebook: <published URL>
MCQ 3.15: <paste result line>
Popcorn Hacks 1–3 completed during class and copied to notebook: yes
Homework tested: <cases or runs and observed output>

Keep the Homework Hack self-contained so the published notebook can be reviewed without depending on the earlier lesson cells. The homework below is a written prompt and starter code to transfer into your notebook; work through it independently.

Homework Hack (independent): SFI Backend QA Simulator

Build a reusable randomized QA simulator for the SFI automotive backend.

The simulator should work with:

  • structured SFI part records,
  • multiple backend actions,
  • existing spec numbers,
  • repeated test runs,
  • and duplicate-spec handling during creation.

The final runner should clearly show which record and action were selected and what backend-style result occurred.

Copy this starter into your personal submission notebook after class. Complete it there, run multiple tests, and include the output. This is a reference block, not an in-page runner:

// Homework Hack - SFI Backend QA Simulator

const parts = [
    {
        "product_name": "Replacement Flywheels",
        "category": "Auto Racing",
        "spec_number": "1.1"
    },
    {
        "product_name": "Multiple Disc Clutch Assemblies",
        "category": "Drag Racing",
        "spec_number": "1.2"
    },
    {
        "product_name": "Racing Flywheel Record",
        "category": "Auto Racing",
        "spec_number": "2.1"
    }
];

const actions = [
    "GET/search",
    "POST/create",
    "PUT/update",
    "DELETE/remove"
];

const existingSpecNumbers = ["1.1", "2.1"];
const testCount = 5;

// Build and test your QA simulator below.

Grading Plan (1 Point Total)

Part Points What earns the points
Popcorn Hack 1 0.10 Valid random record IDs with correct explanation of the possible range/repeats.
Popcorn Hack 2 0.15 Random selection of a complete structured SFI record with correct displayed fields.
Popcorn Hack 3 0.20 Random part/action selection with correct action-dependent behavior.
MCQ 0.15 All questions attempted and result line included; full credit for 4/4.
Homework Simulator 0.40 Reusable multi-run QA simulator handles API actions and duplicate-spec behavior correctly.
Total 1.0  

Quick Validation Checklist

  • Every generated record ID/index is valid.
  • Repeated random values are treated as normal behavior.
  • Structured records remain intact when selected.
  • Multiple API actions are exercised in the final simulator.
  • The complete possible output/range is explained.
  • MCQ result line and the published personal notebook link are ready for the Notes field.
  • Section 3 College Board pseudocode has been reviewed and compared with the JavaScript solution.
  • Publish your notebook with submission frontmatter; submit the published homework notebook URL through the Link Submission form below.

7. Lesson Revisions

  • Kept one consistent SFI automotive/backend QA context across all examples and hacks.
  • Organized examples from simple random integers to structured random backend actions.
  • Added a reference guide and AP CSP alignment that connects RANDOM(a, b) to JavaScript.
  • Added an interactive MCQ checkpoint before the final simulator.
  • Kept homework runners as starter scaffolds rather than completed solutions.
  • Added three editable prize-wheel Code Runner Challenges for random prizes, inclusive ranges, and player coin checks.
  • Placed College Board pseudocode alongside the AP CSP requirements in Section 3.
  • Placed the SFI lesson theme within the lesson plan.
  • Switched the assignment frontmatter to link submission and added the assignment creator UIDs.

Revision Made: Aligned the nine sections with the 1.02 lesson format and aligned submission metadata/instructions with link-based homework submission.

  • Embedded the three live Popcorn Hacks beside their teaching examples; made homework a noninteractive notebook starter and documented personal notebook submission frontmatter.

8. Feedback Evidence

Feedback Received: The lesson model should include the seven core stages, an optional theme stage, required College Board pseudocode, and autograder frontmatter.


9. References

College Board. AP Computer Science Principles Course and Exam Description, Topic 3.15 Random Values and the AP CSP Exam Reference Sheet.

MDN Web Docs. Math.random(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random.

Submit Assignment

Need to update a submission later? Open the submissions dashboard.