给定是词典中的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