3.15 Random Values ๐ŸŽฒ

Random Values = unpredictable numbers (like rolling dice!)


๐Ÿ”ฅ The Magic Formula

Random number from 1 to 6 (like a dice)

Math.floor(Math.random() * 6) + 1

How it works:

  • Math.random() gives a decimal like 0.4827
  • * 6 makes it bigger: 2.8962
  • Math.floor() chops off decimals: 2
  • + 1 shifts it up: 3 โœ…

Want different numbers? Change the 6!

  • Math.floor(Math.random() * 10) + 1 โ†’ 1 to 10
  • Math.floor(Math.random() * 100) + 1 โ†’ 1 to 100
%%javascript
// ๐ŸŽฒ Roll a dice! Run this cell multiple times!

const diceRoll = Math.floor(Math.random() * 6) + 1;
console.log(`You rolled: ${diceRoll}`);

%%javascript
// ๐ŸŽฏ Try it yourself! Change the numbers

// Random number 1-10
const random10 = Math.floor(Math.random() * 10) + 1;
console.log(`Random 1-10: ${random10}`);

// Random number 1-100
const random100 = Math.floor(Math.random() * 100) + 1;
console.log(`Random 1-100: ${random100}`);

๐ŸŽฎ Random Choice from a List

Pick one random item from an array:

const colors = ["red", "blue", "green"];
const randomColor = colors[Math.floor(Math.random() * colors.length)];

The trick: colors.length tells you how many items (3), so you get 0, 1, or 2!

%%js

// ๐ŸŽจ Pick a random color!

const colors = ["๐Ÿ”ด Red", "๐Ÿ”ต Blue", "๐ŸŸข Green", "๐ŸŸก Yellow"];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
console.log(`You got: ${randomColor}`);

// Run multiple times to see different colors!

๐ŸŽฏ 50/50 Chance (Coin Flip)

if (Math.random() < 0.5) {
    console.log("Heads");  // 50% chance
} else {
    console.log("Tails");  // 50% chance
}

Why 0.5? Math.random() gives 0 to 0.999โ€ฆ, so half the time itโ€™s less than 0.5!

%%js

// ๐Ÿช™ Flip a coin!

if (Math.random() < 0.5) {
    console.log("๐Ÿช™ Heads!");
} else {
    console.log("๐Ÿช™ Tails!");
}

// Run it 10 times - you'll get about 5 heads and 5 tails!

๐ŸŽ Challenge: Loot Box!

Use random to make a simple game where you have different chances:

  • 70% chance = Common
  • 25% chance = Rare
  • 5% chance = Legendary
%%javascript
// ๐ŸŽ Open a loot box!

const chance = Math.random();  // Get random number 0 to 0.999...

if (chance < 0.70) {
    console.log("โšช Common Item");  // 0 to 0.70 = 70%
} else if (chance < 0.95) {
    console.log("๐Ÿ”ต Rare Item");   // 0.70 to 0.95 = 25%
} else {
    console.log("๐ŸŸก Legendary!");  // 0.95 to 1 = 5%
}

// Run this many times - legendary is rare!
<IPython.core.display.Javascript object>