문제
내가 빌딩하는 테스트 벤치의 일환으로, 나는 정수 값의 히스토그램 (문제를 해결하기 위해 알고리즘을 위해 취한 반복 수)을 계산할 간단한 클래스를 찾고 있습니다. 대답은 다음과 같은 것으로 불러야합니다.
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);
}
그러나 이것은 빈 쓰레기통을 남길 것입니다
다른 팁
BastardsAnt의 제안을 바탕으로 나는 깔끔하고 상당히 일반적인 포장지를 생각해 냈습니다.
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);
});
제휴하지 않습니다 StackOverflow