通过真假各种可能的组合进行迭代?

时间:2017-07-01 13:20:22

标签: math combinatorics

我们说我有4个布尔人。

如何制作一个遍历每个可能组合的for循环,例如

1000
0100
0010
0001
1100//etc...

1 个答案:

答案 0 :(得分:0)

如果编程语言无关紧要,那么至少有两种方法可以生成组合列表。

首先列举整数类型的位模式,可以按如下方式进行。

1. Let n be the number of boolean variables.
2. Enumerate each number from 0 to 2^n-1.
3. For each of these numbers, say e, generate an assignment of the
   boolean variables where the i-th variable is assigned true
   if and only if the i-th bit of e is set.
4. Save each of these assignments.

其次是迭代生成可以按如下方式完成的赋值。

1. Initialize a list l with one entry; the single entry
   represents a potential assignment of the variables.
2. While there are entries in the list in which there is an unassigned
   variable, execute the following steps, where c is a list of candidate assignments.
3. For each entry in l which has an unassigned variable, say e, generate two entries in c,
   namely one where the unassigned variable is set to true and one in
   which it is set to false. Remove e from l.
4. Merge the candidate list c into l.