生成所有可能的二进制组合

时间:2015-08-26 17:36:50

标签: java eclipse for-loop methods binary

我正在尝试为前两个字节生成所有可能的二进制组合。

00000000 00000001
00000000 00000010
00000000 00000011

我有一个我正在上课的课程,但它显然根本不起作用。我不能让方法在生成时返回输出。

我让下面的代码正常工作,但仅用于计算1个字节。如何更改此值以计算2个字节的所有可能结果?

package referenceCode;

public class BinaryGenerator {

private int val = 0; private int[] values = new int[]{0,1}; //This method converts the Binary Pattern output into a char[] so that it can be printed out to a file public int[] binaryPatternToString() { int numBits = 8; values[0] = 0; values[1] = 1; int[] returned = null; for (int i = 1; i < numBits; i++) { returned = binaryGenerator(i); for (int j = 1; j < numBits; j++) { } } return returned; } private int[] binaryGenerator(int iVal) { int[] moreValues = new int[values.length * 2]; int start = (int)Math.pow(2, iVal); for (int j = 0; j < values.length; j++) { moreValues[j * 2] = values[j] << 1; moreValues[j * 2 + 1] = values[j] << 1 | 1; } values = moreValues; for (int value : values) { System.out.println(Integer.toBinaryString(value)); } return moreValues; }}

将它作为递归方法而不是带有for循环的方法会更好或更有效吗?

2 个答案:

答案 0 :(得分:4)

您可能知道所有java Integers都基于二进制数。因此,对于2个字节,最大数量是2 ^ 16 = 65536.只需遍历所有数字并获取它们的二进制值,必要时将它们填充为零,最后将它们存储在列表中。这将返回所有可能的2字节二进制数。对于更多字节,只需增加字节变量。

实现:

int bytes = 2;
int nBits = bytes * 8;
int maxNumber = 1 << nBits; //this equals 2^nBits or in java: Math.pow(2,nbits)
ArrayList<String> binaries = new ArrayList<>();
for (int i = 0; i < maxNumber; i++) {
    String binary = Integer.toBinaryString(i);
    while (binary.length() != nBits) {
        binary = "0" + binary;
    }
    binaries.add(binary);
}
System.out.println(binaries);

为简单起见,包含了bytes和nBits变量。

您还可以使用递归方法。以空字符串开头,递归地将0或1添加到字符串的开头并继续,直到达到所需的位数:

public static ArrayList<String> getBinaries(int bits, String current) {
    ArrayList<String> binaries = new ArrayList<>();

    if (current.length() == bits) {
        binaries.add(current);
        return binaries;
    }

    //pad a 0 and 1 in front of current;
    binaries.addAll(getBinaries(bits, "0" + current));
    binaries.addAll(getBinaries(bits, "1" + current));

    return binaries;
}

您可以使用:getBinaries(16,"")调用此函数2个字节。

答案 1 :(得分:1)

我冒昧地编写了自己的版本,因此您可以看到更简单的方法来生成这些数字。

这里最难的部分是增加布尔值列表。一般情况下,它就像添加1.你增加一个插槽,如果它已经是1,你继续前进到10s插槽,依此类推。否则,你只需遍历所有的posobilities,打印出每个posobilities。

import java.util.ArrayList;
import java.util.List;

public class Sandbox {

    // list of booleans to represent each bit
    private static List<Boolean> bytes = new ArrayList<>();

    public static void main(String[] args) {
        // initialize the list to all false
        for(int i = 0; i < 16; i++) {
            bytes.add(false);
        }

        // calculate the number of permutations
        int numPermutations = (int)Math.pow(2, 16);

        // print the first permutation
        print();

        // loop through all permutations
        for(int i = 0; i < numPermutations; i++) {
            // increment the 2 bytes
            increment();

            // print the current permutation
            print();
        }
    }

    /**
     * Prints out the current permutation
     */
    private static void print() {
        // loop through the bytes
        for(Boolean bool : bytes) {
            // print 1 or 0
            if(bool)
                System.out.print(1);
            else
                System.out.print(0);

        }

        // end the line
        System.out.println();
    }

    /**
     * Increment the bytes
     */
    private static void increment() {
        // set increment position to the end of the list
        int position = bytes.size() - 1;

        // loop through changing next digit if necessary, stopping
        // if the front of the list is reached.
        do {
            bytes.set(position, !bytes.get(position));
        } while(!bytes.get(position--) && position >= 0);
    }
}