【问题标题】:check array contains the same numbers检查数组是否包含相同的数字
【发布时间】:2018-01-15 15:29:50
【问题描述】:

我正在尝试制作一个简单的骰子游戏。它完全在控制台中。 用户可以设置无限数量的骰子。然后游戏必须告诉所有骰子同时变为 6 的次数。

我试过这样的,

    int i = 0;
    int[] throws = new int[4000];
    bool success = false;
    do
    {
        throws[1] = dice.Next(1, 7);
        throws[2] = dice.Next(1, 7);
        throws[3] = dice.Next(1, 7);
        throws[4] = dice.Next(1, 7);
        throws[5] = dice.Next(1, 7);
        throws[6] = dice.Next(1, 7);

        if (Array.TrueForAll(throws, 6))
        {
            success = true;
        }
        i++;
    } while (success != true);

但是 trueforall 说失败并带有谓词,我一直无法完全理解。

还有其他方法吗?

有点卡在这里..希望有人可以帮助解决这个问题。

【问题讨论】:

  • 参见文档here。第二个参数应该是一个函数,如果您要检查的项目是否成立,则返回 true,否则返回 false。
  • 如果 throws 是 bool[],则需要 throws.TrueForAll(b => b)
  • @vc74 throws are int[] throws = new int[4000];
  • @andrelange91 那是你的第二个问题。您应该只使您的数组尽可能大,否则您的 TrueForAll 将检查每个额外的索引 - 它们可能并不都满足您的谓词。
  • @andrelange91 然后你可以使用: if (throws.All(i => (i == 6))

标签: c# predicate dice


【解决方案1】:

谓词是一种将一个对象/变量作为参数的方法,检查其条件并返回truefalse.. 现在回到问题:

而不是做:

 if (Array.TrueForAll(throws, 6))

做:

 if (Array.TrueForAll(throws, x => x == 6))

但这是什么?

x => x == 6

正是我们正在谈论的谓词

是一个 lambda,可以读作:

在变量 X 中获取数组中的每个元素。现在计算 X == 6

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-30
  • 2021-01-03
  • 2012-09-14
相关资源
最近更新 更多