【问题标题】:How to generate a Boolean array with every possible true or false combination如何使用每个可能的真假组合生成布尔数组
【发布时间】:2019-02-12 13:23:24
【问题描述】:

我输入了一系列数字,例如 1 2 3 4,我可以将它们相加或相减,然后我指定它必须等于 4。我使用布尔数组来表示这两个操作:True = '+'和假='-'。我在 while 循环中使用方法调用,它将在布尔数组中生成 true 或 false 的所有可能组合。我的代码确实会生成组合来解决数字系列,但是当数字系列为 15 或更大时,该方法花费的时间太长并且无法解决数字系列。

有没有人对我如何提高效率并能够解决超过 20 个整数的数字序列提出建议?

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

这个方法也是这样调用的:

while (hasNextOper(oper)) {

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

    }

【问题讨论】:

标签: java performance combinations


【解决方案1】:

您的 hasNextOper 方法似乎在这些数组值之间循环:

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

注意这些变化是如何以与二进制数相同的模式变化的:000、001、010、...。因此,您应该能够取整数(long 类型最多可为您提供 64 位;如果您想要更多,请使用BigInteger,但这有点复杂)。

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

【讨论】:

    猜你喜欢
    • 2017-02-05
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多