本文介绍了创建大小为 n 的布尔数组的所有可能方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够创建一个组合的布尔数组并通过程序运行它以查看它是否有效.如果没有,那么我将其处理掉并转到下一个组合.我的问题是我不知道如何创建这个数组,因为 n 可以在 1-1000 之间的任何地方相等.所以我打算使用 Integer.toBinaryString 但这将不起作用,因为当它超过 32 时它太大了.任何帮助都会很棒.

I need to be able to create a boolean array of one combination and run it through a program to see if it works. If not then I dispose of it and go to the next combination. My issue is that I don't know how to create this array because n can be equal anywhere from 1-1000. So I was planning on using Integer.toBinaryString but that won't work due to its too big when it gets to past 32.Any help would be greatful.

谢谢!

推荐答案

已接受的答案"指出

经过测试,这适用于较高的 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).您可以使用

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

上面的代码将无限期地打印我超过了Integer.MAX_VALUE但是,这可以使用 BigInteger 或用于循环的类似数据结构轻松纠正.下面的代码适用于 n

Code above will indefinitely print i exceeded Integer.MAX_VALUEHowever 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);
    }
}

这篇关于创建大小为 n 的布尔数组的所有可能方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 16:46