473,657 Members | 2,423 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dice rolling problem

Hello, I'm doing an exercise to simulate rolling a pair of dice 36,000
times, then count and display how many times the simulation rolls each
possible sum.

For some reason each time I run my simulation, one or more of my sums is
zero, which is highly unlikely. So I'm sure there's a bug in my code. But
I can't tell what it is, even after re-reading it several times. Can
someone give me a hint?

Here is my code:

static void SimulateDiceRol ls()
{
// When you roll two dice, there are 11 possible sums:
// 2, 3, ..., 10, 11, 12. Define an array of 13 elements
// where the first two elements are unused, but the third element
// where index equals 2, corresponds to sum = 2, and so on.
// make sure they're initialized to 0, which C# does by default
int[] sum = new int[13];

// for 36,000 times, roll two dice, calculate the sum,
// and increment the index corresponding to that sum.
int currentResult = 0;
for (int numberOfRolls = 1; numberOfRolls <= 36000; ++numberOfRolls )
{
currentResult = RollTwoDice();
++sum[currentResult];
}

// print how many times each sum comes up and what percent of the time
// to a 3 decimal precision that sum comes up
for (int sumIndex = 2; sumIndex <= 12; ++sumIndex)
{
Console.WriteLi ne("{0,5} {1,5} {2:F3}", sumIndex, sum[sumIndex],
(double)sum[sumIndex] / 36000 * 100);
}
}

// return the sum of two randomly generated integers from 1 to 6
// inclusive
static int RollTwoDice()
{
Random r = new Random();
return r.Next(1, 7) + r.Next(1, 7);
}

Thanks in advance,
Jose
Jan 5 '07 #1
17 9593
I changed my code to the folllowing which fixes the problem.
But I don't care about getting the program to work as much as I would like
to know what I did wrong in my first example. Can anyone help explain what
I did wrong in the code from my earlier post?

Thanks!

Working code:

static void SimulateDiceRol ls()
{
// When you roll two dice, there are 11 possible sums:
// 2, 3, ..., 10, 11, 12. Define an array of 13 elements
// where the first two elements are unused, but the third element
// where index equals 2, corresponds to sum = 2, and so on.
// make sure they're initialized to 0, which C# does by default
int[] sum = new int[13];
Random r = new Random();

// for 36,000 times, roll two dice, calculate the sum,
// and increment the index corresponding to that sum.
int currentResult = 0;
for (int numberOfRolls = 1; numberOfRolls <= 36000; ++numberOfRolls )
{
currentResult += r.Next(1, 7);
currentResult += r.Next(1, 7);
++sum[currentResult];
currentResult = 0;
}

// print how many times each sum comes up and what percent of the time
// to a 2 decimal precision that sum comes up
for (int sumIndex = 2; sumIndex <= 12; ++sumIndex)
{
Console.WriteLi ne("{0,5} {1,5} {2:F3}", sumIndex, sum[sumIndex],
(double)sum[sumIndex] / 36000 * 100);
}
}
Jan 5 '07 #2
I believe the problem is your usage of Random; for tight-loops you need
to use a single instance, otherwise successive objects in a similar
time interval (tiny amounts of time apart) will have the same seed.

This shoud fix it:

static readonly Random _rand = new Random();
static int RollTwoDice()
{
return _rand.Next(1,7) + _rand.Next(1,7) ;
}

Marc

Jan 5 '07 #3
I see. So my super short loop would call RollTwoDice(), increment a
counter, and then, say, before the next millisecond, it would call
RollTwoDice(), perhaps many times before a new seed would be used. So
given that usually two or three out of 11 dice sums never got rolled in
36,000 tries, I'd guess one number got rolled several thousand times in a
row, then another number several thousand times after that, and so on.

I'll make a version of my original program that will tell me if this is the
case.

Thanks for pointing me in what really looks like the right direction!

-Jose
Jan 5 '07 #4
I put a Console.Write() statement in my loop which tells me which number was
generated i each iteration. This makes each iteration take a lot longer,
but still each "random" number was generated dozens of times in a row. So
you were right!

Once again, thanks Marc.

-Jose
Jan 5 '07 #5
An oft-found trap ;-p

Just for completeness, Jon Skeet has a StaticRandom class in one of
his tool-bags which may be of interest to anyone using occasional
random numbers (useful where this type of private Random instance is
inconvenient due to e.g. threading / scoping constraints). Assuming
your code is not threaded, then for this type of tight loop I would
recommend the solution already posted (a "local" fixed instance),
purely to avoid the overhead of locking etc associated with static
utilities; OK, an uncontested lock is still fast, but not locking at
all (where it isn't necessary) is faster. If your code *is* threaded,
then you should probably note the risk of two calls to the *same*
Random.Next at the same time, which may not be safe; in this case you
could either:
* do your own local locking in the static method
* use StaticRandom
* (my preferred option) give each thread a separate *instance* of the
DiceRoller class (or whatever), so that they don't conflict and each
has an uncontested (instance) _rand that doesn't need locking.

In the general case, static methods should be thread safe. Looking at
http://msdn2.microsoft.com/en-us/library/2dx6wyd4.aspx, it doesn't
make any claims about thread-safety, so I have to assume that it isn't
thread-safe, which means the code I posted also isn't. Oops.

http://www.yoda.arachsys.com/csharp/miscutil/
http://www.yoda.arachsys.com/csharp/threads/

Marc
Jan 5 '07 #6
"Jose Durazo" <jo************ **@josenstacy.c omha scritto nel messaggio
news:Ok******** ******@TK2MSFTN GP02.phx.gbl...
Hello, I'm doing an exercise to simulate rolling a pair of dice 36,000
times, then count and display how many times the simulation rolls each
possible sum.

For some reason each time I run my simulation, one or more of my sums is
zero, which is highly unlikely. So I'm sure there's a bug in my code.
But I can't tell what it is, even after re-reading it several times. Can
someone give me a hint?
For the truth you are rolling the same dice 72000 times, since the random
object is always the same.

Why you do a r.Next(1, 7) while a dice has only 6 faces?
Jan 5 '07 #7
OP>Hello, I'm doing an exercise to simulate rolling a pair of dice
36,000
OP>times,
For the truth you are rolling the same dice 72000 times, since the
random object is always the same.
The random object being the same doesn't allow you to make this
statement.
Mathematically, unless the dice know about eachother and the results
directly influence eachother, then there is no difference in rolling
one die twice versus rolling two dice once. I think therefore that the
OPs statement is perfectly valid. However, given I already posted the
answer to this, you could state that "many of your successive
observations are based on the same roll of 2 dice, themselves
separate", meaning that the OP might have observed "1+5,1+5,...1+5 ,
3+3, 3+3, ..., 3+3, 4+4, 4+4, ... 4+4" etc.
Why you do a r.Next(1, 7) while a dice has only 6 faces?
The upper number to Random.Next is exclusive; hence Next(1,7) will
return a number in the range "[1,7)", or the set "{1,2,3,4,5,6}" .

Marc
Jan 5 '07 #8
r.Next(x,y) returns a minimum of x and a maximum of < y, so in this
case it will return 1 to 6.

Fabio Z wrote:
"Jose Durazo" <jo************ **@josenstacy.c omha scritto nel messaggio
news:Ok******** ******@TK2MSFTN GP02.phx.gbl...
Hello, I'm doing an exercise to simulate rolling a pair of dice 36,000
times, then count and display how many times the simulation rolls each
possible sum.

For some reason each time I run my simulation, one or more of my sums is
zero, which is highly unlikely. So I'm sure there's a bug in my code.
But I can't tell what it is, even after re-reading it several times. Can
someone give me a hint?

For the truth you are rolling the same dice 72000 times, since the random
object is always the same.

Why you do a r.Next(1, 7) while a dice has only 6 faces?
Jan 5 '07 #9
Ammendment; I see what you are trying to say in your "same dice 72000
times", but it is still incorrect; the OPs code actually rolls 36000
dice, each twice

Again, at the math level it isn't going to make the slightest damned
difference, but yes; to *truly* roll two dice you would need 2 Random
instances - however, you would need to be very careful when
initialising them, e.g.

Random dice1 = new Random(), dice2 = new Random(dice1.Ne xt());

A simple dice1 = new Random(), dice2 = new Random() would almost
always end up reporting doubles each time "1+1, 5+5, 3+3" etc due to
the seed and call-frequency being equal. But again: mathematically it
makes no distinction (1 twice versus 2 once), *provided* Random
provides a uniform distribution and lack-of-memory-function (i.e.
regardless of the first roll, the second roll is still uniform [over
the bigger picture; successive calls to Random are obviously
predictable on a 1-by-1 basis if you know the initial seed]).

Marc
Jan 5 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1951
by: lawentzel | last post by:
I am new to PHP and am an avid RPG gamer. I am looking to use PhpMyChat to be able to game with friends all over the US. With that having been said, PhpMyChat seems to offer a lot of what I am looking for. It allows you to send a message to individual players (chatters). It allows for actions using "/me". The only thing it really needs is the capability to do a dice roll. Can someone point me to a site which might have some examples...
101
6365
by: Elijah Cardon | last post by:
Let's say I have m dice having n sides, such that n^m is not going to bust int as a datatype. With m=4 and n=6, an outcome might be {2, 5, 1, 2}. What is a good way to represent this in c so that I can check cases by brute force? EC
1
6211
by: lenest | last post by:
I need help writing a program.... You are to write a python program to accomplish the following: a.. Play a dice game of Craps using a random number generator to simulate the roll of the dice, the code for the rolling of the dice should take place in a user written module named rolldice. b.. The rules of the game are as follows:
4
4119
by: vegtard | last post by:
simple question. is it possible to write a script that rolls a six sided dice? if this is possible, is it possible to tell it to roll the six sided dice 4 times and ignore the dice that rolled the lowest score? if you want to know, i am working on a script to create a dungeons and dragons character :)
38
9117
by: d0ugg | last post by:
I'm writing a program that will have to roll the dice A and dice B one million times, and calculate the percentage of times that the dies will be equal. I'm having trouble to figure out how the percentage will work. Here is my code: #include <ctime> #include <iostream> using namespace std;
2
3390
by: sunnydude | last post by:
Anybody know how to write a 3 dice rolling program like this Sample output Welcome to the dice roller! First of all, please enter a seed for the random number generator. This should be a positive integer: 3 How many times would you like me to roll the 3 dice?
0
8394
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8825
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7327
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6164
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1615
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.