3

I was following a tutorial on random number generation in Visual C# 2010 Express as a console app and ran into an issue.

The code matches the tutorial I was watching as far as I can tell with 5 overviews.

The idea is that it will take built in random seed function and generate 100 values with it. The program will be storing the random number (a double) as a KEY for a DICTIONARY and a int VALUE to show the number of duplicates. This system will print analytical data about the duplicates, the mean, and the distribution.

//PROGRAM SCOPE
private const int Count = 100;
// MAIN CLASS SCOPE
var standardRnd = new Random(20);
var list = new Dictionary<double,int>();

//In a for loop till Count-1
  var rand = standardRnd.NextDouble();

            if (!list.ContainsKey(rand))
                list.Add(rand, 1);
            else
            {
                list[rand]++;
                duplicate++;
            }

When I run the program the console will activate just fine but I wont print anything to the screen. After a second or so It will throw an exception and highlight this code snippet.

 sum += rand * list[rand];

ERROR: The given key was not present in the dictionary.

Logically it makes sense to me. Do you guys see anything wonky?

Thank you for any help you can give.

FULL CODE:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Random_RnD
{
class Program
{



    static void Main(string[] args)
    {

        var standardRnd = new Random(20);

        var min = 1.0;
        var max = 0.0;
        var valueCounter = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        var list = new Dictionary<double,int>();
        var duplicate = 0;
        var iterations = 0;

        var timeStart = DateTime.Now;

        //Do Stuff
        for (int x = 0; x < Count; x++)
        {

            var rand = standardRnd.NextDouble();

            if (!list.ContainsKey(rand))
                list.Add(rand, 1);
            else
            {
                list[rand]++;
                duplicate++;
            }

            iterations++;

        }

        var timeStop = DateTime.Now;
        var elapseTime = TimeSpan.FromTicks((timeStop-timeStart).Ticks);

        //Analytics
        var sum = 0.0;

        foreach (var kvp in list)
        {
            var rand = kvp.Key;

            if (rand < min)
                min = rand;
            if(rand>max)
                rand = max;

            if (rand >= 0.0 && rand < 0.1)
                valueCounter[0]++;
            if (rand >= 0.1 && rand < 0.2)
                valueCounter[1]++;
            if (rand >= 0.2 && rand < 0.3)
                valueCounter[2]++;
            if (rand >= 0.3 && rand < 0.4)
                valueCounter[3]++;
            if (rand >= 0.4 && rand < 0.5)
                valueCounter[4]++;
            if (rand >= 0.5 && rand < 0.6)
                valueCounter[5]++;
            if (rand >= 0.6 && rand < 0.7)
                valueCounter[6]++;
            if (rand >= 0.7 && rand < 0.8)
                valueCounter[7]++;
            if (rand >= 0.8 && rand < 0.9)
                valueCounter[8]++;
            if (rand >= 0.9 && rand <= 1.0)
                valueCounter[9]++;

            sum += rand * list[rand];
        }



        Console.WriteLine("{0:###,###,###} Iteration took: {1:D2}min:{2:D2}sec:{3:D2}msec",
                         iterations, elapseTime.Minutes, elapseTime.Seconds, elapseTime.Milliseconds);

        Console.WriteLine("    {0}\n    {1}", min, max);

        Console.WriteLine("    0.0 to 0.1 = {0:###,###,###}", valueCounter[0]);
        Console.WriteLine("    0.1 to 0.2 = {0:###,###,###}", valueCounter[1]);
        Console.WriteLine("    0.2 to 0.3 = {0:###,###,###}", valueCounter[2]);
        Console.WriteLine("    0.3 to 0.4 = {0:###,###,###}", valueCounter[3]);
        Console.WriteLine("    0.4 to 0.5 = {0:###,###,###}", valueCounter[4]);
        Console.WriteLine("    0.5 to 0.6 = {0:###,###,###}", valueCounter[5]);
        Console.WriteLine("    0.6 to 0.7 = {0:###,###,###}", valueCounter[6]);
        Console.WriteLine("    0.7 to 0.8 = {0:###,###,###}", valueCounter[7]);
        Console.WriteLine("    0.8 to 0.9 = {0:###,###,###}", valueCounter[8]);
        Console.WriteLine("    0.9 to 1.0 = {0:###,###,###}", valueCounter[9]);

        var avg = sum / (double)iterations;

        Console.WriteLine("\nStatistics:");
        Console.WriteLine(" Mean = {0}", avg);
        Console.WriteLine(" Duplicates = {0}", duplicate);

        Console.ReadKey();



    }
}

}

1
  • Once upon a time I spent hours debugging some code, only to find out the problem was caused by missing braces (if (condition) statement1; statement2; instead of if (condition) { statement1; statement2; }. Now every time I see code that omits braces out of pure laziness, (if (condition) statement instead of if (condition) { statement }) it sends me into a homicidal rage. Nov 14, 2012 at 18:45

1 Answer 1

2

The problem is here:

if (rand>max)
    rand = max;

This assigns 0 to rand. But 0 isn't guaranteed to be in the dictionary.

You meant max = rand;.


There is also a much easier way to find the minimum and maximum values in a collection by using LINQ:

var keys = list.Keys;
double min = keys.Min();
double max = keys.Max();
2
  • Or alternatively you could ditch the if statement and write max = Math.Max(rand, max) Nov 14, 2012 at 18:48
  • smacks my face thank you so much! Also thank you for the LINQ init, I just getting into LINQ, delegates, and Lamdas and it is so nice! Nov 14, 2012 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.