Small Basic: Dice Simulation

Dice Simulation

If you roll a fair dice, you’ll get any number between 1 and 6. In this example, we’ll write a program that simulates the rolling of a dice. In particular, we’ll roll a dice 10000 times and keep track of how many times each face appears. The program demonstrates how to use array for counting, or tallying, the results of an experiment. The complete program is shown in the Listing.

Listing:

 1 ' Dice.sb

 2 ' Simulates rolling of a dice

 3

 4 ROLL_COUNT = 10000    ' How many times to roll

 5

 6 For N = 1 to 6        ' Set dice[1]=dice[2]=...=dice[6]=0

 7   dice[N] = 0

 8 EndFor

 9

10 For N = 1  to ROLL_COUNT        ' Rolls the dice

11   num = Math.GetRandomNumber(6) ' Gets the outcome (face)

12   dice[num] = dice[num] + 1     ' Increments face count

13 EndFor

14

15 ' Displays the simulation results

16 TextWindow.WriteLine("Frequency Table:")

17 For N = 1 to 6

18   TextWindow.Write( N + ": " + dice[N] )

19   TextWindow.CursorLeft = 10

20   TextWindow.WriteLine(dice[N] / ROLL_COUNT)

21 EndFor

   

Output:

Frequency Table:

1: 1640   0.164

2: 1670   0.167

3: 1638   0.1638

4: 1684   0.1684

5: 1680   0.168

6: 1688   0.1688

 

The program uses an array, named dice, to hold the number of occurrences of the six faces of the dice. At the end, dice[1] will show how many times number 1 appeared, dice[2] will show how many times number 2 appeared, and so on.

The program starts by initializing dice[1] through dice[6] to 0 (lines 6-8). It then starts a For loop that iterates 10000 times (line 10). In each iteration, it gets a random number, num, between 1 and 6 and increments dice[num] (lines 11-12).  For example, if num=1, dice[1] is incremented by 1; if num=2, dice[2] is incremented by one, and so on.

At the end of the simulation, the program prints the simulation results (lines 16-20). It does that by running a For loop that runs from 1 to 6 (line 17). For each value of the loop counter, N, the program prints N, dice[N], and dice[N]/10000, which is the probabilty of the N’th face showing up. The output of the program shows that six faces of the dice have “approximately” the same chance of occurrence.

   

TRY IT OUT!

Modify the Dice.sb program to simulate rolling a pair of dice. You need to keep track of the sum of the numbers that show up on the two faces. Make the ouput of the program look like this:

Sum   Count   Probability

2         284      0.0284

3         561      0.0561

4         841      0.0841

...

11      511       0.0511

12      272       0.0272

  

Do you have any questions? Ask us! We're full of answers and other fine things!

Head to the Small Basic forum to get the most answers to your questions: 

https://social.msdn.microsoft.com/Forums/en-US/smallbasic/threads/   

And go to https://blogs.msdn.com/SmallBasic to download Small Basic and learn all about it!

  

Small and Basically yours

- Ninja Ed & Majed Marji