c# - C#中整数数据的简单直方图生成

标签 c# histogram

作为我正在构建的测试台的一部分,我正在寻找一个简单的类来计算整数值的直方图(算法解决问题所采用的迭代次数)。答案应该这样称呼:

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] );
}

我很惊讶谷歌搜索没有找到一个巧妙的解决方案,但也许我没有搜索正确的东西。有通用的解决方案吗?还是值得我自己动手?

最佳答案

你可以使用 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);
}

虽然这会留下空箱子

关于c# - C#中整数数据的简单直方图生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/926067/

相关文章:

gnuplot : using a logarithmic axis for a histogram

python - 使用具有两列以上的 df 的子图中的堆叠条形图

c# - 如何在 .NET 中将提示/标记写入 WAV 文件

c# - Task.Factory.StartNew,保持同一线程

c# - 隐式类型;为什么只是局部变量?

python - Google 图表中的玫瑰图

c++ - 打印直方图 C++

c# - 如何异步运行 3 个进程,当一个返回期望值时停止其他两个并继续执行程序?

c# - C# 编译器是否足够智能来优化此代码?

python - 是否可以将数字放在 matplotlib 直方图之上?