布尔变量的所有可能组合组合、布尔、变量

2023-09-11 02:19:37 作者:靠边站 别挡信号

我试图找到一种算法,可以让我做到以下几点: 想象一下,我有10布尔变量,我想尝试每一种组合,因为我的目标是要找到任意组合,这将给其结果是对我的方法真一(此方法有很多的限制,这就是为什么我要测试每一个可能的组合,并且如果没有组合,将解决这个问题,那么我想通知用户这一点)。 我希望这是可以理解的!

I'm trying to find an algorithm that will allow me to do the following: Imagine I have 10 boolean variables, and I want to try every combination, since my goal is to find ANY combination which will give as a result to one of my methods true (This method has lots of restrictions, which is why I want to test every possible combinations, and if there are no combinations that will solve the problem, then I want to notify the user this). I hope it is understandable!

推荐答案

我终于想出了一个更有效的方法:使用二进制数: 比方说,我想测试所有可能的布尔组合出8个变量: 如果我选择做下面我会测试每一种组合:

I finally came up with a more efficient method: Using binary numbers: Let's say I want to test all possible boolean combinations out of 8 variables: If I pick do the following I'll get to test every combination:

    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,其中可再psented作为布尔$ P $。在这个例子中,如果没有发现相结合的方法,将返回null。

This will go from 0 to 255, which in binary means going from 00000000 to 11111111 where each digit take the value 0 or 1, which can be represented as boolean. In this example if there's no combination found the method will return null.