gpt4 book ai didi

java - 创建大小为 n 的 boolean 数组的所有可能方式?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:20:18 24 4
gpt4 key购买 nike

我需要能够创建一个包含一个组合的 boolean 数组,并通过程序运行它以查看它是否有效。如果不是,那么我将其处理掉并转到下一个组合。我的问题是我不知道如何创建这个数组,因为 n 可以在 1-1000 之间的任何地方相等。所以我打算使用 Integer.toBinaryString 但由于它超过 32 时太大而无法使用。任何帮助都将不胜感激。

谢谢!

最佳答案

接受的答案”指出

Tested and this will work for high values of n, such as 10000 and so on.

但这不正确

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 > 31i 以来,它将永远循环重复前 2^31 个组合将溢出并且永远不会到达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);
}
}

关于java - 创建大小为 n 的 boolean 数组的所有可能方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com