62,046
社区成员
发帖
与我相关
我的任务
分享
public class Choose
{
/// <summary>
/// 使用的选择
/// </summary>
private int currentIndex = -1;
/// <summary>
/// 使用的权重
/// </summary>
private int currentWeight = 0;
/// <summary>
/// 权重的最大公约数
/// </summary>
private int gcdWeight;
/// <summary>
/// 权重总和
/// </summary>
private int sumWeight;
/// <summary>
/// 最大权重
/// </summary>
private int maxWeight;
/// <summary>
/// 权重数量
/// </summary>
private Dictionary<int, int> dic = new Dictionary<int, int>
{
{ 1, 3 },
{ 2, 3 },
{ 3, 4 }
};
/// <summary>
/// 权重数量
/// </summary>
private int count;
public Choose()
{
count = dic.Count;
maxWeight = dic.Values.Max();
var weightArray = dic.Values.ToArray();
gcdWeight = 1; //计算最大公约数GetDivisor(weightArray);
sumWeight = weightArray.Sum();
}
public int GetKey(int nums)
{
int dicKey = 0;
nums = nums % sumWeight == 0 ? sumWeight : nums % sumWeight;
int count = 0;
while (count != nums)
{
count++;
dicKey = GetKey();
}
return dicKey;
}
private int GetKey()
{
while (true)
{
currentIndex = (currentIndex + 1) % count;
if (currentIndex == 0)
{
currentWeight = currentWeight - gcdWeight;
if (currentWeight <= 0)
{
currentWeight = maxWeight;
if (currentWeight == 0)
{
return 0;
}
}
}
if (dic[currentIndex] >= currentWeight)
{
return dic[currentIndex];
}
}
}
}