Night 9: Roll the dice
Anda sudah menyelesaikan malam ini dalam Python atau pseudocode. Hasilnya dihitung untuk keduanya. Berlatihlah lagi jika Anda mau.
Tonight: roll the dice
- Games need surprises. Tonight your pet rolls a dice.
- You will learn one thing: random numbers with
RAND.
Words for tonight
| Word | Meaning |
|---|---|
| random | you cannot know it before; it can be different each time |
| RAND | the 9618 function that gives a random number |
| INT | keep only the whole number part: INT(3.72) is 3 |
RAND gives a real number
RAND(6)gives a number from 0 up to 6, but never 6 itself. For example3.72.INTcuts off the part after the point.INT(3.72)is3.- So
INT(RAND(6))is 0, 1, 2, 3, 4 or 5. Add 1, and you get a dice: 1 to 6.
DECLARE Roll : INTEGER
Roll ← INT(RAND(6)) + 1
OUTPUT "Your pet rolled ", Roll
- Press Run a few times. The number changes!
Pick from an array
- A random index picks a random element.
DECLARE Toys : ARRAY[1:3] OF STRING
DECLARE Index : INTEGER
Toys[1] ← "ball"
Toys[2] ← "kite"
Toys[3] ← "box"
Index ← INT(RAND(3)) + 1
OUTPUT "Let's play with the ", Toys[Index]
How does the checker test random code?
- The checker cannot know your number. So it checks the rules:
- Is the output a number from 1 to 6? Did you use
RAND? - So use the variable names the task gives you.
Random plus a loop
- Put
RANDinside aWHILEloop to roll again and again.
DECLARE Roll : INTEGER
Roll ← 0
WHILE Roll <> 6
Roll ← INT(RAND(6)) + 1
OUTPUT "Rolled ", Roll
ENDWHILE
OUTPUT "Six!"
- Now roll some dice in the tasks!
Kesulitan 2/5 · 140 koin + bonus kecil pada penyelesaian pertama hari ini
Your pet rolls a dice. Put a random whole number from 1 ke 6 in Roll, using INT(RAND(6)) + 1. Output Roll.
Klik Jalankan untuk melihat output di sini.
Kesulitan 2/5 · 140 koin + bonus kecil pada penyelesaian pertama hari ini
Pick a random index from 1 ke 3. Output Tonight: and the snack at that index.
Klik Jalankan untuk melihat output di sini.
Kesulitan 2/5 · 140 koin + bonus kecil pada penyelesaian pertama hari ini
Roll two dice: DiceA dan DiceB, each from 1 ke 6. Put their sum in Total and output it.
Klik Jalankan untuk melihat output di sini.
Kesulitan 3/5 · 200 koin + bonus kecil pada penyelesaian pertama hari ini
Roll a dice again and again until you get a 6. Count the rolls in Rolls. After the loop, output Six!.
Klik Jalankan untuk melihat output di sini.