计算可能发生的随机动作

时间:2019-03-14 15:03:14

标签: c#

我有一个列举一些可能动作的枚举

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)
        };

        List<ActionWithPossibility> actionsWithPossibilities = new List<ActionWithPossibility>() {
            new ActionWithPossibility(Action.Stay, 30),
            new ActionWithPossibility(Action.MoveLeft, 10),
            new ActionWithPossibility(Action.MoveRight, 60)
        };

        List<ActionWithPossibility> actionsWithPossibilities = new List<ActionWithPossibility>() {
            new ActionWithPossibility(Action.Stay, 30),
            new ActionWithPossibility(Action.MoveLeft, 60),
            new ActionWithPossibility(Action.MoveRight, 10)
        };

有2件重要的事情:

  • 可能性的总和为100。
  • 可以执行更多或更少的操作。因此,动作量未知。

通过此方法调用随机动作时

    public void NextAction(List<ActionWithPossibility> actionsWithPossibilities)
    {
        int randomNumber = random.Next(0, 100);

        // ...

        Action targetAction = null; // ?
    }

是否有一种方法来计算操作(不使用ifs)?我考虑过这种设置:

  • 动作A 30
  • 动作B 10
  • 动作C 60

我可以总结一下当前行动的前辈,并会得到结果

  • 动作A 0-30
  • 动作B 30-40
  • 动作C休息

但是我不知道如何通过代码来计算动作。一些帮助会很棒。

这可能是

的重复项

Percentage Based Probability

但是正如我之前提到的,可能采取的行动数量是未知的,所以我不能选择三个if语句。也许有一些技巧可以使用一些数学运算来完全避免if语句。

2 个答案:

答案 0 :(得分:3)

Expected 2 arguments, but got 1.

答案 1 :(得分:0)

如果您的操作在列表中,并且想要将生成的随机数映射到正确的对象。您可以这样想:

LINQ:

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.