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

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

谢谢!

接受的答案 ”说明了这一点

经测试,这将适用于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)); } } 

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

上面的代码将无限期地打印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); } } 

我已经在另一个问题上找到了你的问题的答案,我已经适应了你:

 public class Foo { 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)); } } } 

会产生:

 [true, true, true] [true, true, false] [true, false, true] [true, false, false] [false, true, true] [false, true, false] [false, false, true] [false, false, false] 

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