简体   繁体   中英

How to generate a Boolean array with every possible true or false combination

I input a series of numbers like 1 2 3 4, which i can either add or subtract to each other and then I specify it must equal 4. I use a Boolean array to represent the two operations: True = '+' and False = '-'. I use a method call in a while loop that will generate every possible combination of true or false in the Boolean array. My code does generate combinations to solve the series of numbers, but when the number series are 15 or greater the method takes far too long and will not solve the series of numbers.

Does anyone have a suggestion on how i could make this more efficient and be able to solve number series with more than 20 Ints?

private static boolean hasNextOper(boolean[] oper) {
    for (int i = 0; i < oper.length; i++) {

        if (oper[i]) {
            oper[i] = false;
        } else {
            oper[i] = true;
            return true;
        }
    }
    return false;
}

This method is also being called like this:

while (hasNextOper(oper)) {

        if (isTarget(oper, numbers, target, order)) {
            displayResults(oper, numbers, target, order);
            return;
        }

    }

Your hasNextOper method seems to be cycling through these array values:

{false, false, true }
{false, true , false}
{false, true , true }
{true , false, false}
...

Note how these change in the same pattern as a binary number: 000, 001, 010, .... Therefore you should be able to take an integer (a long type gives you up to 64 bits; if you want more, use a BigInteger but that's a bit more complicated).

    // Example: generate all possible combinations in an array of 20 booleans.
    final int length = 20;
    for (long n = 0; n < (1 << length); n++) {
        oper = longBitsToBoolArray(n, length);
        // ... now do things with oper
        // ...
    }

static bool[] longBitsToBoolArray(long bits, int length) {
    bool[] oper = new bool[length];
    for (int i = 0; i < length; i++)
        oper[i] = ((bits >>> i) & 1) != 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM