Search code examples
c#histogram

Simple histogram generation of integer data in C#


As part of a test bench I'm building, I'm looking for a simple class to calculate a histogram of integer values (number of iterations taken for an algorithm to solve a problem). The answer should be called something like this:

Histogram my_hist = new Histogram();

for( uint i = 0; i < NUMBER_OF_RESULTS; i++ )
{

    myHist.AddValue( some_result );
}

for( uint j = 0; j < myHist.NumOfBins; j++ )
{
     Console.WriteLine( "{0} occurred {1} times", myHist.BinValues[j], myHist.BinCounts[j] );
}

I was suprised a bit of googling didn't turn up a neat solution but maybe I didn't search for the right things. Is there a generic solution out there or is it worth rolling my own?


Solution

  • You could use SortedDictionary

    uint[] items = new uint[] {5, 6, 1, 2, 3, 1, 5, 2}; // sample data
    SortedDictionary<uint, int> histogram = new SortedDictionary<uint, int>();
    foreach (uint item in items) {
        if (histogram.ContainsKey(item)) {
            histogram[item]++;
        } else {
            histogram[item] = 1;
        }
    }
    foreach (KeyValuePair<uint, int> pair in histogram) {
        Console.WriteLine("{0} occurred {1} times", pair.Key, pair.Value);
    }
    

    This will leave out empty bins, though