給定是詞典中的N個項目集合及其與其關聯的事件。 現在,我必須根據其總概率爲每個項目分配完全X個插槽,但每個項目至少需要1個插槽。將N個項目至少分配給一個集合
這裏是我想出來的:
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
public static class Program
{
public static void Main(string[] args)
{
var dict = new Dictionary<char,int>();
dict.Add('a' , 10); dict.Add('b' , 0);
dict.Add('c' , 4); dict.Add('d' , 1);
dict.Add('e' , 9); dict.Add('f' , 0);
var distributionMap = Distribute(dict , 40);
}
public static Dictionary<T,int> Distribute<T>(Dictionary<T,int> occurMap , int slots)
{
var freeSlots = slots - occurMap.Count;
var total = occurMap.Sum(x => x.Value);
var distMap = new Dictionary<T,int>();
foreach(var pair in occurMap)
{
var probability = (double)pair.Value/total;
var assignedSlots = probability * freeSlots;
distMap[ pair.Key ] = (int)(1 + assignedSlots);
}
Debug.Assert(distMap.Select(x => x.Value).Sum() == slots);
return distMap;
}
}
但是斷言觸發,從double
到int
轉換在某些點截斷的概率。
如何根據其數量將所有插槽至少映射一次到物品?
概率是一個分數,所以它應該是一個分數或乘以100來得到一個百分比。總數需要轉換爲double,因爲如果total是一個整數,c#會將pair.value/total轉換爲整數。你真的希望pair.value/total是一個非整數。 – jdweng
Math.Ceiling()也許? – Master117
@jdweng爲什麼我需要一個百分比?此外,隨着我投一個操作數翻倍,概率已經是雙倍。 – nonsensation