创建大小为n的布尔数组的所有可能方式?

Fis*_*k12 7 java arrays combinations boolean

我需要能够创建一个组合的布尔数组,并通过程序运行它以查看它是否有效.如果没有,那么我将其丢弃并转到下一个组合.我的问题是我不知道如何创建这个数组,因为n可以等于1-1000.所以我打算使用Integer.toBinaryString,但由于它太过大而无法工作到32岁.任何帮助都会很棒.

谢谢!

SGa*_*Gal 5

“已接受的答案 ”指出:

经过测试,这将适用于较高的n值,例如10000等。

但这是不正确的

public static void main(String[] args) {
    final int n = 3;
    for (int i = 0; i < Math.pow(2, n); i++) {
        String bin = Integer.toBinaryString(i);
        while (bin.length() < n)
            bin = "0" + bin;
        char[] chars = bin.toCharArray();
        boolean[] boolArray = new boolean[n];
        for (int j = 0; j < chars.length; j++) {
            boolArray[j] = chars[j] == '0' ? true : false;
        }
        System.out.println(Arrays.toString(boolArray));
    }
}
Run Code Online (Sandbox Code Playgroud)

n > 31它将永远循环时,重复前2 ^ 31个组合,因为i它将溢出并且永远不会到达Math.pow(2, n)。您可以轻松地用

public static void main2(String[] args){
        int n = 32;
        for (int i = 0; i < Math.pow(2, n); i++){
            if (i == Integer.MIN_VALUE) {
                // i overflows
                System.out.println("i exceeded Integer.MAX_VALUE");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

上面的代码将无限期地打印,i exceeded Integer.MAX_VALUE 但是可以使用BigInteger循环的类似数据结构或类似的数据结构轻松地纠正此问题。以下代码适用于n <= Integer.MAX_VALUE

public static void main(String[] args) {
    final int n = 32;
    BigInteger bi = BigInteger.ZERO;
    BigDecimal rows = new BigDecimal(Math.pow(2, n));
    while (bi.compareTo(rows.toBigInteger()) < 0) {
        String bin = bi.toString(2);//Integer.toBinaryString(i);
        while (bin.length() < n)
            bin = "0" + bin;
        char[] chars = bin.toCharArray();
        boolean[] boolArray = new boolean[n];
        for (int j = 0; j < chars.length; j++) {
            boolArray[j] = chars[j] == '0' ? true : false;
        }
        System.out.println(Arrays.toString(boolArray));
        bi = bi.add(BigInteger.ONE);
    }
}
Run Code Online (Sandbox Code Playgroud)