Простая генерация гистограммы целочисленных данных в C#
в рамках стенда я строю, я ищу простой класс для вычисления гистограммы значений integer (числа итераций для алгоритма для решения задачи). Ответ следует назвать примерно так:--2-->
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] );
}
Я был удивлен, что немного гуглить не оказалось аккуратным решением, но, возможно, я не искал правильные вещи. Есть ли общее решение или стоит прокатить свой собственный?
4 ответов
вы можете использовать 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);
}
это оставит пустые бункеры, хотя
основываясь на предложении BastardSaint, я придумал аккуратную и довольно общую обертку:
public class Histogram<TVal> : SortedDictionary<TVal, uint>
{
public void IncrementCount(TVal binToIncrement)
{
if (ContainsKey(binToIncrement))
{
this[binToIncrement]++;
}
else
{
Add(binToIncrement, 1);
}
}
}
так что теперь я могу сделать:
const uint numOfInputDataPoints = 5;
Histogram<uint> hist = new Histogram<uint>();
// 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<uint, uint> histEntry in hist.AsEnumerable())
{
Console.WriteLine("{0} occurred {1} times", histEntry.Key, histEntry.Value);
}
потребовалось некоторое время, чтобы понять, как сделать его общим (для начала я просто преодолел SortedDictionary
конструктор, который означал, что вы можете использовать его только для uint
ключи).
вы можете использовать Linq:
var items = new[] {5, 6, 1, 2, 3, 1, 5, 2};
items
.GroupBy(i => i)
.Select(g => new {
Item = g.Key,
Count = g.Count()
})
.OrderBy(g => g.Item)
.ToList()
.ForEach(g => {
Console.WriteLine("{0} occurred {1} times", g.Item, g.Count);
});
этот код дает графическое представление значений массива.
using System;
// ...
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Cyan;
int[] array = { 2, 2, 2 };
PrintHistogram(array);
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("Press any key to quit . . . ");
Console.ReadKey(true);
}
static void PrintHistogram(int[] array)
{
int largest = 0;
for (int i = 0; i < array.Length; i++)
largest = Math.Max(largest, array[i]);
largest--;
// Bars
while (largest >= 0)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] > largest)
Console.Write("|\t");
else
Console.Write("\t");
}
largest--;
Console.WriteLine();
}
Console.WriteLine();
// Numbers
for (int i = 0; i < array.Length; i++)
Console.Write(array[i] + "\t");
Console.WriteLine();
}