【问题标题】:All possible combinations of boolean variables布尔变量的所有可能组合
【发布时间】:2012-09-11 10:01:15
【问题描述】:

我正在尝试找到一种算法来允许我执行以下操作: 想象一下,我有 10 个布尔变量,我想尝试每一种组合,因为我的目标是找到任何组合,这将使我的一种方法成为真的(这种方法有很多限制,这就是我想测试的原因每个可能的组合,如果没有可以解决问题的组合,那么我想通知用户)。 我希望它是可以理解的!

【问题讨论】:

    标签: c# algorithm boolean


    【解决方案1】:

    试试这个:

    for (int i = 0; i < (1 << 10); i++)
    {
        bool b1 = (i & (1 << 0)) != 0;
        bool b2 = (i & (1 << 1)) != 0;
        bool b3 = (i & (1 << 2)) != 0;
        bool b4 = (i & (1 << 3)) != 0;
        ...
    
        if (MyMethod(b1, b2, b3, b4, ...))
        {
            // Found a combination for which MyMethod returns true
        }
    }
    

    当然,您也可以使用 LINQ:

    var result = from b1 in new[] { false, true }
                 from b2 in new[] { false, true }
                 from b3 in new[] { false, true }
                 from b4 in new[] { false, true }
                 ...
                 where MyMethod(b1, b2, b3, b4, ...)
                 select new { b1, b2, b3, b4, ... };
    

    【讨论】:

    • 我要睡觉了,已经快凌晨 3 点了,我得早起,明天会告诉你,但据我所知,我认为它可能会起作用! :) 谢谢
    • 有什么方法可以应用它,但可以应用到许多 X 变量(这意味着我不知道我将拥有多少个布尔值,它们取决于用户选择的内容)。我对语法不是很熟悉,这就是我问的原因:)
    【解决方案2】:

    我终于想出了一个更有效的方法:使用二进制数: 假设我想测试 8 个变量中所有可能的布尔组合: 如果我选择执行以下操作,我将测试每个组合:

    public string CombinationFinder()
    {
        for (int i = 0; i < 2 ^ 8; i++)
        {
            String ans = Convert.ToInt32(i, 2).ToString();
            if (myMethod(ans))
            {
                return ans;
            }
        }
        return null;
    }
    

    这将从 0 变为 255,二进制表示从 00000000 变为 11111111 其中每个数字取值 0 或 1,可以表示为布尔值。在此示例中,如果未找到组合,则该方法将返回 null。

    【讨论】:

      【解决方案3】:

      我知道这是一个老问题,但 waclock 的答案无法编译(C# 中没有指数运算符)。 dtb 的答案达到了 99%,但不处理未知数量的布尔值,这就是这个答案所提供的:

      var props = typeof(TypeWithBooleans).GetProperties().Where(prop => prop.PropertyType == typeof(bool)).ToArray();
      
      for (var i = 0; i < (1 << props.Length); ++i)
      {
          var combination = Enumerable.Range(0, props.Length).Select(j => (i & (1 << j)) != 0).ToArray();
          if (MyMethod(combination)) {
              // handle match
          };
      }
      

      这假设您关心的所有布尔值都限制在单个类/结构中,并且 MyMethod 使用 params 数组。

      【讨论】:

        【解决方案4】:

        这样定义一个类:

        class Bint
        {
          int num;
          public bool this[int num]
          {
            get {return num << n & 0x1 == 1;}
          }
          public int Num
          {
            get {return num;}
            set {num = value;}
          }
        }
        

        并遍历数字:

        Bint n = new Bint();
        for (int i = 0; i < Math.pow(2,10); i++)
        {
         n.Num = i;
         f(n[0],n[1]...);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-06-25
          • 1970-01-01
          • 1970-01-01
          • 2018-03-31
          • 1970-01-01
          • 2012-12-08
          • 1970-01-01
          相关资源
          最近更新 更多