布尔变量的所有可能组合 [英] All possible combinations of boolean variables

查看:182
本文介绍了布尔变量的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种算法,可以让我做到以下几点: 想象一下,我有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.

这篇关于布尔变量的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆