生成二进制序列

时间:2015-07-03 12:49:03

标签: java binary

我想生成所有可能的二进制数字序列,其中列表中的每个序列都限制为特定数量的1,并且有零填充以使每个列表具有相同的长度。

例如,如果序列应该是4个数字长,并且有2个,那么所有序列都将是:

1100 1010 1001 0110 0101 0011

并保留数字前面的零。

4 个答案:

答案 0 :(得分:3)

这可以使用递归函数调用来解决:

public class BinarySequences {

    public static void main(String[] args) {

        final int numCount = 4; 
        final int oneCount = 2; 

        checkSubString(numCount, oneCount, "");

        for (String res : results) {
            System.out.println(res);
        }
    }

    private static List<String> results = new ArrayList<>();

    private static void checkSubString(int numCount, int oneCount, String prefix) {
        if ((numCount >= oneCount) && (oneCount >= 0)) {
            if (numCount==1) {
                if (oneCount==1) {
                    results.add(prefix + "1");
                } else {
                    results.add(prefix + "0");
                }
            } else {
                checkSubString(numCount-1, oneCount  , prefix + "0");
                checkSubString(numCount-1, oneCount-1, prefix + "1");
            }
        }
    }


} 

答案 1 :(得分:2)

如果你想保留0,那么只需添加填充:

int end = 100; //Change this
for (int i = 0; i <= end; i++) {
    String bytestring = Integer.toBinaryString(i);
    String padding = "00000000000000000000000000000000";
    bytestring = padding.substring(0, 32 - bytestring.length()) + bytestring;
    System.out.println(bytestring);
}

答案 2 :(得分:1)

试试这个:

//Edit your min and max, e.g. Integer.MAX_VALUE and Integer.MIN_VALUE
int min = 0;
int max = 10;

for(int i = min; i < max; i++){
    //Make 16 bit long binary Strings
    String s = String.format("%16s", Integer.toBinaryString(i)).replace(' ', '0');

    //Make 4 bits long chunks
    List<String> chunks = new ArrayList<>();
    Matcher matcher = Pattern.compile(".{0,4}").matcher(s);
    while (matcher.find()) {
        chunks.add(s.substring(matcher.start(), matcher.end()));
    }

    StringBuilder b = new StringBuilder();
    for (String c : chunks) {
        //Here you can count the 1 and 0 of the current chunk with c.charAt(index)
        b.append(c);
        b.append(" ");
    }
    System.out.println(b.toString());
}

答案 3 :(得分:1)

需要org.apache.commons.lang.StringUtils,但这只是一个简短的:

final int digits = 4;
final int onesrequired = 2;

int maxindex = (int) Math.pow(2, digits);

for (int i = 0; i < maxindex; i++) {
    String binaryStr = Integer.toBinaryString(i);

    if (StringUtils.countMatches(binaryStr, "1") == onesrequired) {
        System.out.print(String.format("%" + digits + "s", binaryStr).replace(' ', '0') + " ");
    }
}