C#中整数数据的简单直方图生成 [英] Simple histogram generation of integer data in C#
本文介绍了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?
推荐答案
您可以使用SortedDictionary
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
这篇关于C#中整数数据的简单直方图生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文