Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically decide how many loops I want?

Tags:

java

for-loop

Here is the subject:

I have a LinkedList list, if the list has 3 elements, I'd like to list an entire truth table for it, for instance:

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

and if the list has 4 or more elements, I would like to generate a more large table.

But I got stuck here:

I know writing loops like this can generate the entire table:

       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);
                    }
                }
            }
        }

but I can't change the number of loops based on the list size, and I think writing special cases for this is unacceptable, so is there an alternative way to do this??

like image 655
shengy Avatar asked Dec 11 '22 22:12

shengy


1 Answers

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.

like image 88
Prasanth Avatar answered Dec 24 '22 09:12

Prasanth