Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get array elements to display correctly C#

Tags:

arrays

c#

I'm doing a small assignment for school and I'm having a bit of trouble. The purpose of the program is to sum up the roll of 2 random numbers 36000 times. The numbers should be in the range of 1-6 (to simulate dice).

We're then to count the frequency of each summed value and display it to the console.

Seemed easy enough except I'm getting an unusual output when I run the program. When I run the program in debug it works fine so I'm a little stumped how to find the problem...

I'm using an array of counters to count how many times a value is rolled. The output i'm getting looks like this : 5888 0 6045 0 6052 0 5969 0 6010 0 6036 (each value is on a newline I just typed it like this to save space)

When I run debug (F11) and then hit F5 after single stepping I get the desired output :
973 2022 3044 3990 4984 6061 4997 4030 2977 1954 968

using System;

public class DiceRollUI
{

    public static void Main(string[] args)
    {
        DiceRoll rollDice = new DiceRoll();
        Random dice1 = new Random();                    //dice 1
        Random dice2 = new Random();                    //dice 2

        int len = 36000;
        while( len > 0) {

            rollDice.DiceRange((uint)dice1.Next(1, 7) + 
                (uint)dice2.Next(1,7));                 //sum the dice and pass value to array

        --len;
    }

    rollDice.DisplayRange();                        //display contents of counter array
    Console.ReadLine();
  }//end Main method

}//end class DiceRollUI

using System;

public class DiceRoll
{
    private uint[] rolledDice = new uint[11];           //counter array to count number of rolls

    public void DiceRange(uint diceValue)
    {
        ++rolledDice[diceValue - 2];                    //offset values to place in correct element
    }//end method DiceRange

    public void DisplayRange()
    {
        for(int i = 0; i < rolledDice.Length; i++)
            Console.WriteLine("{0}", rolledDice[i]);

    }//end method DisplayRange

}//end class RollDice
like image 991
WBuck Avatar asked Feb 27 '14 02:02

WBuck


People also ask

Can we print whole array in C?

This program will let you understand that how to print an array in C. We need to declare & define one array and then loop upto the length of array. At each iteration we shall print one index value of array. We can take this index value from the iteration itself.

Which is correct way of accessing array elements?

Array elements can be accessed using the position of the element in the array. The array can have one or more dimensions.

Can we print array in C without loop?

Ya, we can. If the array size is fixed, for example if the array's size is 6. Then you can print the values like printf(a[0]) to printf(a[5]).

How do you store values in an array?

Storing Data in Arrays. Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.


2 Answers

This is because of the way Random() constructor works. Based on MSDN:

By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.

So your two instances of Random actually generate the same number every time.

One sulution to that is to use only one instance of Random for both dice rolls as you don't really need 2 of them.

Random dice = new Random();                    

int len = 36000;
while (len > 0)
{
    rollDice.DiceRange((uint) dice.Next(1, 7) +
                       (uint) dice.Next(1, 7)); //sum the dice and pass value to array

    --len;
}
like image 189
Szymon Avatar answered Nov 14 '22 20:11

Szymon


Here's an alternate way to get a random seed. You're doing everything correctly, except your random number generators look like they aren't being "truly" random, so I would try something like this (give one random the system-based seed and then give the other random a random from random1):

static void Main(string[] args)
{
    DiceRoll rollDice = new DiceRoll();
    Random dice1 = new Random();                    //dice 1
    System.Threading.Thread.Sleep(100);             //get a different seed for dice 2
    Random dice2 = new Random();                    //dice 2

    int len = 36000;
    ...
 }

This gave me the results you expect. The reason the program is working correctly after you take one step into debugging is because you initialize one random, which gets a random seed, and then when you take another step, the other random is generated with a different seed from your system's clock.

enter image description here

Note: for future debugging, you could notice that the random dice totals are only factors of two, which could lead to the guess that the randoms are generating the same value.

like image 27
davidsbro Avatar answered Nov 14 '22 20:11

davidsbro