4

这是主题:

我有一个LinkedList list,如果列表有 3 个元素,我想为它列出一个完整的真值表,例如:

a b c   <---   the three elements in list
0 0 0
0 0 1
0 1 0
1 0 0
1 1 1
1 1 0
1 0 1
0 1 1

如果列表有 4 个或更多元素,我想生成一个更大的表。

但我被困在这里:

我知道像这样编写循环可以生成整个表:

       for (int a = 0; a < 2; a++){
            for (int b = 0; b < 2; b++) {
                for (int c = 0; c < 2; c++) {
                    for (int d = 0; d < 2; d++) {
                        System.out.println(a + " " + b + " " + c + " " + d);
                    }
                }
            }
        }

但是我不能根据列表大小更改循环数,而且我认为为此编写特殊情况是不可接受的,那么有没有其他方法可以做到这一点?

4

3 回答 3

12

simple solution if you just want a truth table:

code:

int len = 3;
int num = (int)Math.pow(2, len);
for(int i=0; i<num; i++){
    // http://stackoverflow.com/a/4421438/1273830
    System.out.println(String.format("%"+len+"s", Integer.toBinaryString(i)).replace(' ', '0'));
}

Basic digital logic: truth tables are binary number sequences.

于 2012-09-13T10:11:28.643 回答
1

The number of loops needs to match the number of elements. There are two ways to solve this.

  • Use recursion so that there is one loop and the method calls itself for the next level of looping.
  • Use a single loop which repeats 2^n times and extracts out the components values.
于 2012-09-13T10:08:41.670 回答
0

我不会为您用 Java 编写它,但这里有一个伪代码,可以让您了解如何递归地解决问题:

l = ['a','b','c']

def f(l, result):
    if len(l) == 0:
        print result
        return
    first = l[0]
    rest = l[1:]
    f(rest, result + [(first,0)])
    f(rest, result + [(first,1)])

f (l, [])

这应该打印如下内容:

[('a', 0), ('b', 0), ('c', 0)]
[('a', 0), ('b', 0), ('c', 1)]
[('a', 0), ('b', 1), ('c', 0)]
[('a', 0), ('b', 1), ('c', 1)]
[('a', 1), ('b', 0), ('c', 0)]
[('a', 1), ('b', 0), ('c', 1)]
[('a', 1), ('b', 1), ('c', 0)]
[('a', 1), ('b', 1), ('c', 1)]
于 2012-09-13T10:17:47.513 回答