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
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).