19.04.2017 Views

Learn to Program with Small Basic

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Random Numbers<br />

Random numbers are used in many applications, like simulations and games.<br />

They’re also used for software testing (<strong>to</strong> see how a program responds <strong>to</strong><br />

different input values) or <strong>to</strong> simulate random events (like the lottery).<br />

The GetRandomNumber() method returns a random integer between one<br />

and the upper limit you pass <strong>to</strong> the method. Using this method, your program<br />

can generate random numbers that you can use in all sorts of exciting<br />

applications, for instance, <strong>to</strong> see whether a troll bops your hero on the<br />

head. Let’s look at some examples.<br />

To simulate a roll of a die, write this:<br />

dice = Math.GetRandomNumber(6)<br />

TextWindow.WriteLine("You rolled: " + dice)<br />

The variable, dice, contains a number between 1 and 6 that’s selected<br />

at random, similar <strong>to</strong> picking it out of a hat (but not the Hogwart’s Sorting<br />

Hat). Run the program several times <strong>to</strong> see for yourself.<br />

To simulate the flip of a coin, you can write this:<br />

coinFlip = Math.GetRandomNumber(2)<br />

TextWindow.WriteLine("Outcome: " + coinFlip)<br />

The variable coinFlip is either 1 or 2. The value 1 represents heads, and<br />

the value 2 represents tails (or the other way around; it’s up <strong>to</strong> you!).<br />

To simulate rolling a pair of dice and finding their sum, you can write<br />

this code:<br />

num1 = Math.GetRandomNumber(6)<br />

num2 = Math.GetRandomNumber(6)<br />

outcome = num1 + num2<br />

TextWindow.Write("You got (" + num1 + "," + num2 + "). ")<br />

TextWindow.WriteLine("The <strong>to</strong>tal is " + outcome)<br />

Although your outcome will be a number between 2 (rolling two 1s)<br />

and 12 (rolling two 6s), don’t make the mistake of writing this:<br />

outcome = 1 + Math.GetRandomNumber(11)<br />

Although this statement gives you a number between 2 and 12, the<br />

probability you’d get from one random number is different from adding<br />

two random numbers <strong>to</strong>gether.<br />

TRY IT OUT 7-5<br />

A bag contains 20 balls numbered from 1 <strong>to</strong> 20. Write a program that simulates<br />

drawing one ball from the bag at random.<br />

92 Chapter 7

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!