Java:如何输出所有可能的二进制组合(256 个不同的序列)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22208514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:19:16  来源:igfitidea点击:

Java: How to output all possible binary combinations (256 different sequences)?

javabinary

提问by user2411290

I need to create a function that outputs all possible binary combinations (2^8 == 256 different sequences of 8 bits.). I'm really stumped on this. I have to do it with nested loops, and am not sure how to go about it. Below is what I tried so far. I was told that I could write this program using 8 nested loops, each one going from 0 to 1; Also, I could try to do this with bit manipulation operators.

我需要创建一个函数来输出所有可能的二进制组合(2^8 == 256 个不同的 8 位序列。)。我真的被这个难住了。我必须用嵌套循环来做,我不知道如何去做。以下是我到目前为止所尝试的。有人告诉我,我可以使用 8 个嵌套循环编写这个程序,每个循环从 0 到 1;另外,我可以尝试使用位操作运算符来做到这一点。

Although what I have below is obviously wrong, I tried my best to show that I at least tried this. I also need to put new line's after each closing bracket, to separate the output.

虽然我下面的内容显然是错误的,但我尽力表明我至少尝试过这一点。我还需要在每个右括号后放置新行,以分隔输出。

The output should look like this:

输出应如下所示:

00000000

00000000

00000001

00000001

00000010

00000010

00000011

00000011

00000100

00000100

...

...

11111110

11111110

11111111

11111111

public static void outputBinary(){

int[][][][][][][][] num = new int[2][2][2][2][2][2][2][2];

    for (int i = 0; i < 2; i++){

    for (int j = 0; j < 2; j++){

    for (int k = 0; k < 2; k++){

    for (int l = 0; l < 2; l++){

    for (int m = 0; m < 2; m++){

    for (int n = 0; n < 2; n++){

    for (int o = 0; o < 2; o++){

    for (int p = 0; p < 2; p++){

        System.out.print(num[i][j][k][l][m][n][o][p]);

    } }}}}}}}

}

}

Thanks for looking.

谢谢你看。

采纳答案by Asaph

No need for the array. Here is a slight modification to your code that will output all the permutations.

不需要数组。这是对将输出所有排列的代码的轻微修改。

for (int i = 0; i < 2; i++){
  for (int j = 0; j < 2; j++){
    for (int k = 0; k < 2; k++){
      for (int l = 0; l < 2; l++){
        for (int m = 0; m < 2; m++){
          for (int n = 0; n < 2; n++){
            for (int o = 0; o < 2; o++){
              for (int p = 0; p < 2; p++){
                System.out.println("" + i + j + k + l + m + n + o + p);
              }
            }
          }
        }
      }
    }
  }
}

Do you haveto use nested loops? Because this is trivially easy when you simply take advantage of the fact that the binary representation of all the numbers from 0 through 255 cover every permutation.

必须使用嵌套循环吗?因为当您简单地利用从 0 到 255 的所有数字的二进制表示涵盖每个排列这一事实时,这非常容易。

for (int i=0; i<256; i++) {
    System.out.println(Integer.toBinaryString(i));
}

回答by Smutje

Just print the forvariables (i...p) without accessing this obscure empty array.

只需打印for变量 ( i...p) 而不访问这个晦涩的空数组。

回答by nikis

Well, if it's OK to use some built-in classes, you can do this in the following way:

好吧,如果使用一些内置类没问题,你可以通过以下方式做到这一点:

for (int i=0; i<256; i++){
    System.out.println(Integer.toBinaryString(i));
}

And the second way (I believe you should use it, because looking by looking at it you can understand what's under the hood instead of "some magic", it uses bit mask):

第二种方式(我相信您应该使用它,因为通过查看它,您可以了解引擎盖下的内容,而不是“一些魔法”,它使用bit mask):

for (int i=0;i<256;i++){
    int mask = 256;
    while (mask > 0){
        if ((mask & i) == 0){
            System.out.print("0");
        } else {
            System.out.print("1");
        }
        mask = mask >> 1;
    }
    System.out.println();
}

回答by Andy Stabler

Here's my version. It uses recursion to convert base 2 to base 10 through repeated division:

这是我的版本。它使用递归通过重复除法将基数 2 转换为基数 10:

public static void printBin()
{
    for (int i = 0; i < 256; i++) {
        int binary = decToBin(i, "");
        // pad to give length of 8
        System.out.println(String.format("%08d", binary));
    }
}

public static int decToBin(int dec, String bin)
{
    int quot = dec / 2;
    int remainder = dec % 2;
    if (quot == 0)
        return Integer.parseInt("" + remainder + bin);
    return decToBin(quot, "" + remainder + bin);
}

回答by andreban

Heres another way of generating all the values using bit operations

这是使用位操作生成所有值的另一种方法

public static void main(String[] args) {
    int numBits = 8;

    int val = 0;
    int[] values = new int[]{0,1};
    values[0] = 0;
    values[1] = 1;

    for (int i = 1; i < numBits; i++) {
        int[] moreValues = new int[values.length * 2];
        int start = (int)Math.pow(2, i);
        for (int j = 0; j < values.length; j++) {
            moreValues[j * 2] = values[j] << 1;
            moreValues[j * 2 + 1] = values[j] << 1 | 1;
        }
        values = moreValues;
    }

    //print the values
    for (int value: values) {
        System.out.println(Integer.toBinaryString(value));
    }

}

And another way, using bit operations and recursion

另一种方式,使用位操作和递归

private static void generateNumbers(int number, int numBits, int currentBit) {
    if (numBits == currentBit) {
        Integer.toBinaryString(number);
        return;
    }
    currentBit++;

    generateNumbers(number << 1, numBits, currentBit);
    generateNumbers(number << 1 | 1, numBits, currentBit);

}

public static void generateNumbers(int numBits) {
    generateNumbers(0, 8, 1);
    generateNumbers(1, 8, 1);
}

public static void main(String[] args) {
    generateNumbers(8);

}

回答by user4951913

package org.cross.topology;

import java.util.ArrayList;

public class Test {

    public static void main(String[] args) {

        //System.out.println("sushil");
        int digits=3;//Provide number of digits for which you want combinations of 0 and 1
        int noof0and1=(int) Math.pow(2,digits)/*(2^digits)*/,combinations=(int) Math.pow(2,digits),secondloopcounter=0,temp=0;
        String current_char="0";
        int startindex=0,lastindex;

        ArrayList<String> al=new ArrayList<String>(combinations);
        for(int k=0;k<combinations;k++)
        {
            al.add("");
        }

        for(int i=1;i<=digits;i++)
        {
            noof0and1=noof0and1/2;
            while(temp!=combinations)
            {
                temp=temp+noof0and1;
                secondloopcounter++;
            }
            lastindex=noof0and1;
            startindex=0;
            for(int s=0;s<secondloopcounter;s++)
            {
                for(int j=startindex;j<lastindex;j++)
                {
                    String temps=al.get(j)+current_char;
                    al.remove(j);
                    al.add(j, temps);
                }

                    if(current_char.equals("0"))
                    {
                        current_char="1";
                    }
                    else
                    {
                        current_char="0";
                    }
              startindex=lastindex;
              lastindex=lastindex+noof0and1;
            }

            temp=0;
            secondloopcounter=0;
        }

        for(int l=0;l<al.size();l++)
        {
            System.out.println(al.get(l));
        }
    }

}

回答by binglobal

Do in php , very easy Just convert every count of combinations in binary and add as many 0 as required to complete it in a byte representation.

在 php 中做,非常简单只需将每个组合计数转换为二进制,并根据需要添加尽可能多的 0 以在字节表示中完成它。

    for($c=1;$c<=pow(2,8);$c++)
    {
      $bin_str=base_convert($c,10,2);   //converting combination number into binary string
      $len_str=strlen($bin_str);        // Length of string obtained
      for($i=1;$i<=8-$len_str;$i++)
        $bin_str="0".$bin_str;      // adding as many 0 as required to complete in byte format

      echo "<br>".$bin_str;         //Displaying binary values in byte structure

  }

回答by Anish Kumar

Below is the solution using Recursion as an approach in java

下面是在java中使用递归作为一种方法的解决方案

public class NumberOfBinaryPatterns {

    static int[] bitArray = new int[]{0,1};

    public static void main(String args[])
    {   
        System.out.println("Below are the patterns\n");

        int numberOfBits=4;  // It can be any value based on the requirement, In this case we can put this as 8

        drawBinaryPattern(numberOfBits,"");
    }

    private static void drawBinaryPattern(int n,String seed)
    {
        if(n==0){
            System.out.println(seed);
            return;
        }   
        for(int j=0;j<bitArray.length;j++)
        {
            String temp = seed+bitArray[j];
            drawBinaryPattern(n-1,temp);
        }
    }
}