The "accepted answer" states that
Tested and this will work for high values of n, such as 10000 and so on.
But this is incorrect.
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));
}
}
When n > 31
it will loop forever repeating the first 2^31 combinations since i
will overflow and will never reach Math.pow(2, n)
. You can easily test this with
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");
}
}
}
Code above will indefinitely print i exceeded Integer.MAX_VALUE
However this can easily be corrected using BigInteger
or a similar data structure for looping. The code below will work for 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);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…