How to dynamically decide how many cycles I want?

Here is the topic:

I have a LinkedList list , if there are 3 elements in the list, I would like to list the entire truth table for it, for example:

 abc <--- 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 there are 4 or more elements in the list, I would like to create a larger table.

But I'm stuck here:

I know that such write loops can generate the whole 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 cannot change the number of loops based on the size of the list, and I think that writing special cases for this is unacceptable, so is there an alternative way to do this?

+4
source share
3 answers

simple solution if you just want to get 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 sequences of binary numbers.

+12
source

The number of cycles should correspond to the number of elements. There are two ways to solve this problem.

  • Use recursion so that there is one loop, and the method calls itself for the next level of the loop.
  • Use one loop that repeats 2 times n times and retrieves the component values.
+1
source

I will not write it in Java for you, but here is the pseudo code to give you an idea of ​​how to solve the problem recursively:

 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, []) 

This should print something like:

 [('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)] 
0
source

Source: https://habr.com/ru/post/1433974/


All Articles