FutureShocked
FutureShocked

Reputation: 888

Retrieving a single row of a truth table with a non-constant number of variables

I need to write a function that takes as arguments an integer, which represents a row in a truth table, and a boolean array, where it stores the values for that row of the truth table.

Here is an example truth table

Row| A | B | C |
 1 | T | T | T |
 2 | T | T | F |
 3 | T | F | T |
 4 | T | F | F |
 5 | F | T | T |
 6 | F | T | F |
 7 | F | F | T |
 8 | F | F | F |

Please note that a given truth table could have more or fewer rows than this table, since the number of possible variables can change.

A function prototype could look like this

getRow(int rowNum, bool boolArr[]);

If this function was called, for example, as

getRow(3, boolArr[])

It would need to return an array with the following elements

|1|0|1|    (or |T|F|T|)  

The difficulty for me arises because the number of variables can change, therefore increasing or decreasing the number of rows. For instance, the list of variables could be A, B, C, D, E, and F instead of just A, B, and C.

I think the best solution would to be write a loop that counted up to the row number, and essentially changed the elements of the array like it was counting in binary. So that

1st loop iteration, array elements are 0|0|...|0|1|
2nd loop iteration, array elements are 0|0|...|1|0|

I can't for the life of me figure out how to do this, and can't find a solution elsewhere on the web. Sorry for all the confusion and thanks for the help

Upvotes: 1

Views: 391

Answers (1)

Barry
Barry

Reputation: 303750

Ok now that you rewrote your question to be much clearer. First, getRow needs to take an extra argument: the number of bits. Row 1 with 2 bits produces a different result than row 1 with 64 bits, so we need a way to differentiate that. Second, typically with C++, everything is zero-indxed, so I am going to shift your truth table down one row so that row "0" returns all trues.

The key here is to realize that the row number in binary is already what you want. Take this row (having shifted down the 4 to 3):

3 | T | F | F |

3 in binary is 011, which inverted is {true, false, false} - exactly what you want. We can express that using bitwise-or as the array:

{!(3 | 0x4), !(3 | 0x2), !(3 | 0x1)}

So it's just a matter of writing that as a loop:

void getRow(int rowNum, bool* arr, int nbits)
{
    int mask = 1 << (nbits - 1);
    for (int i = 0; i < nbits; ++i, mask >>= 1) {
        arr[i] = !(rowNum & mask);
    }
}

Upvotes: 1

Related Questions