Search code examples
javatruthtable

Truth table array


I'm stuck on how to begin coding this. I want to be able to do the following. It's a classic flipping the coin problem If I flip twice the out comes are:
T T
T F
F T
F F
I want to be able to create an array with one result at a time. To better illustrate this, it should be something like (I'm using Java by the way):
boolean[] cases = new boolean[numberOfFlips]

the first time cases will have: T T.
After I'm done doing other calculations with this result I want to move on and now make cases: T F and proceed with running other calculations.
Can someone guide me in the right direction please? I would greatly appreciate it. An algorithm in any language is fine with me. Thank you for your time! (:


Solution

  • There are many ways to store binary data in Java and it is unclear, what you want to store. If you want to store ALL possible combinations of N flippings, then you need and array new boolean[2^N][N]

    Remember that Java has another syntax for raising to power.

    UPDATE

    Below is the code for storing all combinations of N flips.

    From it you will get an idea how to generate one combination too: from binary representation of combination ordinal number. See comments.

        // number of flips
        // limit it by 31
        int N = 3;
    
        // number of combinations
        // using bitshift to power 2
        int NN = 1<<N;
    
        // array to store combinations
        boolean flips[][] = new boolean[NN][N];
    
        // generating an array
        // enumerating combinations
        for(int nn=0; nn<NN; ++nn) {
    
            // enumerating flips
            for( int n=0; n<N; ++n) {
    
                // using the fact that binary nn number representation
                // is what we need
                // using bitwise functions to get appropriate bit
                // and converting it to boolean with ==
                flips[nn][N-n-1] = (((nn>>n) & 1)==1);
    
                // this is simpler bu reversed
                //flips[nn][n] = (((nn>>n) & 1)==1);
    
            }
    
        }
    
        // printing an array
        for(int nn=0; nn<NN; ++nn) {
    
            System.out.print("" + nn + ": ");
    
            for( int n=0; n<N; ++n) {
                System.out.print(flips[nn][n]?"T ":"F ");
            }
            System.out.println("");
        }