Simple histogram generation of integer data in C#

后端 未结 4 1509
花落未央
花落未央 2020-12-31 19:44

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 pro

4条回答
  •  既然无缘
    2020-12-31 20:11

    Based on BastardSaint's suggestion I came up with a neat and fairly generic wrapper:

    public class Histogram : SortedDictionary
    {
        public void IncrementCount(TVal binToIncrement)
        {
            if (ContainsKey(binToIncrement))
            {
                this[binToIncrement]++;
            }
            else
            {
                Add(binToIncrement, 1);
            }
        }
    }
    

    So now I can do:

    const uint numOfInputDataPoints = 5;
    Histogram hist = new Histogram();
    
    // Fill the histogram with data
    for (uint i = 0; i < numOfInputDataPoints; i++)
    {
        // Grab a result from my algorithm
        uint numOfIterationsForSolution = MyAlorithm.Run();
    
        // Add the number to the histogram
        hist.IncrementCount( numOfIterationsForSolution );
    }
    
    // Report the results
    foreach (KeyValuePair histEntry in hist.AsEnumerable())
    {
        Console.WriteLine("{0} occurred {1} times", histEntry.Key, histEntry.Value);
    }
    

    Took me a while to work out how to make it generic (to begin with I just overrode the SortedDictionary constructor which meant you could only use it for uint keys).

提交回复
热议问题