2017-07-01 40 views
1

假設我有4個布爾值。迭代各種可能的真假組合嗎?

我如何做一個for循環遍歷每個可能的組合,像

1000 
0100 
0010 
0001 
1100//etc... 
+1

你想用特定的編程語言實現某些東西嗎?有很多方法可以生成該查找,這取決於上下文。 – Codor

+0

@Codor我真的不在乎語言,我只想看看它背後的邏輯。 – JorensM

+5

只需從0到15進行計數,並使用按位運算符來提取0到3位。 –

回答

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.