C# 根据可能性计算要执行的随机操作
我有一个枚举,其中包含一些可能的操作C# 根据可能性计算要执行的随机操作,c#,C#,我有一个枚举,其中包含一些可能的操作 internal enum Action { Stay, MoveLeft, MoveRight } 以及一个对象,该对象保存有关此操作的当前机会的信息 internal class ActionWithPossibility { public Action Action { get; } public int ActionChancePercent { get; } public ActionWithPo
internal enum Action
{
Stay,
MoveLeft,
MoveRight
}
以及一个对象,该对象保存有关此操作的当前机会的信息
internal class ActionWithPossibility
{
public Action Action { get; }
public int ActionChancePercent { get; }
public ActionWithPossibility(Action action, int actionChancePercent)
{
Action = action;
ActionChancePercent = actionChancePercent;
}
}
机会从0到100。有机会的一系列行动可能是
List<ActionWithPossibility> actionsWithPossibilities = new List<ActionWithPossibility>() {
new ActionWithPossibility(Action.Stay, 40),
new ActionWithPossibility(Action.MoveLeft, 30),
new ActionWithPossibility(Action.MoveRight, 30)
};
列表
但是正如我之前提到的,可能的操作数量是未知的,所以我不能使用三个if语句。也许有一个技巧是使用一些数学来完全避免if语句。intthreshold=0;
int threshold = 0;
int randomNumber = random.Next(0, 100);
for (var i = 0; i < actionsWithPossibilities.Count; i++)
{
var item = actionsWithPossibilities[i];
threshold += item.ActionChancePercent;
if (randomNumber <= threshold)
{
//first action that's under the defined threshold is placed in result
result = item.Action;
break;
}
}
int randomNumber=random.Next(0,100);
for(var i=0;i if(randomNumber如果您在列表中列出了您的操作,并且希望将生成的随机数映射到正确的对象。您可以这样想:
林克:
actionswith可能性
.OrderBy(x=>x.actionChancePercent)//按递增顺序排序概率
.首先(y=>randomNumber可能重复使用三个if语句:if(randomNumber)我更新了我的问题
List<ActionWithPossibility> actionsWithPossibilities = new List<ActionWithPossibility>() {
new ActionWithPossibility(Action.Stay, 30),
new ActionWithPossibility(Action.MoveLeft, 60),
new ActionWithPossibility(Action.MoveRight, 10)
};
public void NextAction(List<ActionWithPossibility> actionsWithPossibilities)
{
int randomNumber = random.Next(0, 100);
// ...
Action targetAction = null; // ?
}
int threshold = 0;
int randomNumber = random.Next(0, 100);
for (var i = 0; i < actionsWithPossibilities.Count; i++)
{
var item = actionsWithPossibilities[i];
threshold += item.ActionChancePercent;
if (randomNumber <= threshold)
{
//first action that's under the defined threshold is placed in result
result = item.Action;
break;
}
}
actionsWithPossibilities
.OrderBy(x => x.actionChancePercent) // Sort probabilities in increasing order
.First(y => randomNumber <= y.actionChancePercent)
// Find the correct 'bracket' by checking when the
// random number passes the thresholds.