Tuesday, May 26, 2020

How Do I Roll Dice in C#

This application uses one instance of the Random() class in the object rnd. It also allocates enough space to hold the totals for scores 3..18 in the array Rolls[]. Member functions OneDice() returns a value between 1 and 6 - rnd.Next(n) returns values in the range 0..n-1, while ThreeDice() calls OneDice() three times. The constructor for the RollDice() clears the Rolls array then calls ThreeDice() however many times (10 million in this case) and increments the appropriate Rolls[] element. The last part is to print out the generated totals to see that it generates throws in accordance with the probabilities. A 6 sided dice has an average score of 3.5, so three dice should average about 10.5. The totals for 10 and 11 are roughly the same and occur about 12.5% of the time. Here is the output of a typical run. It takes no more than a second. Because its a console application, I included a Console.ReadKey(); To wait until you hit a key before closing. Program Output 3 46665 4 138772 5 277440 6 463142 7 693788 8 971653 9 1157160 10 1249360 11 1249908 12 1159074 13 972273 14 695286 15 463270 16 277137 17 138633 18 46439 Program Listing using System; using System.Collections.Generic; using System.Text; namespace exrand {   Ã‚  Ã‚  Ã‚  public class RollDice   Ã‚  Ã‚  Ã‚  {   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  private Random rnd new Random() ;   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  private int[] Rolls new int[19]; // Holds 3 to 18   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  public int OneDice() {   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  return rnd.Next(6)1;   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  }   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  public int ThreeDice()   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  {   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  return OneDice() OneDice() OneDice() ;   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  }   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  public RollDice(int Count)   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  {   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  int i 0;   Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  Ã‚  for (i3;i

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.