【问题标题】:Fastest way to generate all binary strings of size n into a boolean array?将所有大小为 n 的二进制字符串生成为布尔数组的最快方法?
【发布时间】:2011-12-04 08:07:54
【问题描述】:

例如,如果我想要所有长度为 3 的二进制字符串,我可以像这样简单地声明它们:

boolean[] str1 = {0,0,0};
boolean[] str2 = {0,0,1};
boolean[] str3 = {0,1,0};
boolean[] str4 = {0,1,1};
boolean[] str5 = {1,0,0};
boolean[] str6 = {1,0,1};
boolean[] str7 = {1,1,0};
boolean[] str8 = {1,1,1};

将所有可能的长度为 N 的二进制字符串生成到 布尔数组中的最有效方法是什么?

我不一定需要 最有效的方法,只需要一种对我来说相当高效且易于多线程的方法。

编辑:我应该注意,如果这很重要,我会将它们全部存储在一个 ArrayList 中。

【问题讨论】:

    标签: java binary boolean


    【解决方案1】:

    这是一些生成真值表的代码...(由于数组大小限制,仅适用于 32 位(您可以将大小变量更改为任何值,并将布尔值存储为 1/0,如果需要):

    int size = 3;
        int numRows = (int)Math.pow(2, size);
        boolean[][] bools = new boolean[numRows][size];
        for(int i = 0;i<bools.length;i++)
        {
            for(int j = 0; j < bools[i].length; j++)
            {
                int val = bools.length * j + i;
                int ret = (1 & (val >>> j));
                bools[i][j] = ret != 0;
                System.out.print(bools[i][j] + "\t");
            }
            System.out.println();
        }
    

    【讨论】:

    • 我喜欢这种方法。不过我会再等。
    • @chickeneaterguy:既然你说你想要多线程,我在这里做的一个(或两个)微不足道的改进是:1)将打印移出循环,2 ) 将 i 的类型更改为 AtomicInteger (进行必要的调整)。 #2 然后可以很容易地适应多线程实现。不确定您会通过这种方式获得多少,因为这里的代码块很小。划分线程工作的更好方法可能是为每个线程划分 i 上的范围。
    • @user314104 :我做到了。它很快。我用数组列表代替了它,但我使用了你的方法。谢谢!
    • 只有在 n=31 时才会失败
    【解决方案2】:

    示例:如果您需要长度为 4,那么您必须有 2^4 = 16 个不同的数组。

    您可以使用这个简单的 Java 代码来生成所有数组:

    for (int i=0; i < (Math.pow(2,4)); i++) {
            System.out.println(Integer.toBinaryString(i));
    }
    

    这个的输出:

    0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111

    【讨论】:

      【解决方案3】:

      如果您不关心一次获得所有排列,明智的做法是事先不分配内存,然后简单地编写一个算法来计算 @ 987654321@你想要的,即时。

      这样做的好处:

      • 您可以处理任意数量的排列,而无需分配所有排列
      • 由于该算法不存储任何内容,因此它是线程友好的
      • 您只需为所需的行付费。例如,如果 n=1,000,但您只需要几个排列,这将快得多并且只需要一小部分内存(只需要一行)

      为了让您开始,算法的界面可能如下所示:

      boolean[] getRow(int rowNumber, int nItems)

      因此,您将调用 getRow(5,3) 以从函数返回 str5。我让你来实现细节(这并不难)。

      【讨论】:

        【解决方案4】:

        在函数中实现它-

        static public ArrayList<boolean[]> getBoolArr(int length) {
                int numOptions = 1 << length;
                ArrayList<boolean[]> finalArray = new ArrayList<boolean[]>();
                for(int o=0;o<numOptions;o++) {
                    boolean[] newArr = new boolean[length];
                    for(int l=0;l<length;l++) {
                        int val = ( 1<<l ) & o;
                        newArr[l] = val>0;
                    }
                    finalArray.add(newArr);
                }
                return finalArray;
            }
        

        使用示例-

        ArrayList<boolean[]> res = getBoolArr(2); //2 is your length, change it however you want.
        

        【讨论】:

        • 对我不起作用。如果我使用低数字作为长度,我会超出界限异常。如果我使用大数字,我会得到 1 位数的输出。我不明白所有的
        • 再试一次,它有效。我已将代码放在函数中,因此没有错误的地方(请参阅更新)。如果您有任何问题,请告诉我。 'fredosaurus.com/notes-cpp/expressions/bitops.html 进行解释(它是 c++,但也适用于 java)。
        【解决方案5】:

        这就是我在 Java 中的做法

        public class NbitsStrings {
            int[] arrA;
            public static void main(String[] args) throws java.lang.Exception {
                Scanner input = new Scanner(System.in); //Input the Number Of bits you want.
                int n = input.nextInt();
                NbitsStrings i = new NbitsStrings(n);
                i.nBits(n);
            }
            public NbitsStrings(int n) {
                arrA = new int[n];
            }
            public void nBits(int n) {
                if (n <= 0) {
                    StringBuilder builder = new StringBuilder();
                    for (int value : arrA) {
                        builder.append(value);
                    }
                    String text = builder.toString();
                    System.out.println(text);
                } else {
                    arrA[n - 1] = 0;
                    nBits(n - 1);
                    arrA[n - 1] = 1;
                    nBits(n - 1);
                }
            }
        }
        

        【讨论】:

          【解决方案6】:

          javascript 与重复问题https://stackoverflow.com/questions/42591231/calculate-all-possible-combinations-of-n-off-on-elements 相关的实现。

          与所有数字一样,数字集之间存在关系,一旦识别出模式,就可以使用加法来推导数组集合内特定索引处的数字集之间的关系。

          let [N, n1, n2, n3] = [0, 1, 9, 89];
          
          let [res, max] = [Array(Array(3).fill(N)), Math.pow(2, 3)];
          
          for (let i = 1, curr; i < max; i++) {
          
            if ([1, 3, 5, 7].some(n => n === i)) {
              N += n1;
            }
          
            if ([2, 6].some(n => n === i)) {
              N += n2;
            }
          
            if (i === max / 2) {
              N += n3;
            }
          
            curr = Array.from(String(N), n => +n);
          
            if (N < 100) {
              while (curr.length < 3) {
                curr.unshift(n1 - 1);
              }
            }
          
            res.push(curr);
          
          }
          
          console.log(res);

          【讨论】:

            【解决方案7】:

            这就是我在 Scala 中实现它的方式

            def combinations(n: Int): List[List[Int]] = {
             val numbers = scala.math.pow(2, n).toInt 
             //Convert each to binary equivalent 
             def toBinary(decimal: Int, binary: List[Int]): List[Int] = {
              if (decimal <= 0)
                return le(binary)
              toBinary(decimal / 2, (decimal % 2) :: binary)
             }
             // Size alignment 
             def le(binary: List[Int]):List[Int]=
              {
                if(binary.length!=n) le(0::binary) else binary
              }
             def getCombinations(n: Int, list: List[List[Int]]): List[List[Int]] = {
              if (n < 0)
                return list
              getCombinations(n - 1, toBinary(n, Nil) :: list)
             }
             getCombinations(numbers - 1, Nil)
            }
            

            示例输出:

            • 组合(2) //List(List(0, 0), List(0, 1), List(1, 0), List(1, 1))
            • 组合(3) //List(List(0, 0, 0), List(0, 0, 1), List(0, 1, 0), List(0, 1, 1), List(1 , 0, 0), List(1, 0, 1), List(1, 1, 0), List(1, 1, 1))

            感谢我的朋友 James A。

            【讨论】:

              猜你喜欢
              • 2011-12-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-01-16
              • 1970-01-01
              • 1970-01-01
              • 2010-12-23
              相关资源
              最近更新 更多