我想要生成每一个可能的二进制数字序列,其中列表中的每个序列都被限制为1的特定数,并且有填充的零使每个列表都具有相同的长度。
例如,如果序列应该是4个数字,并且有2个数字,那么所有序列都是:
1100  1010  1001  0110 0101 0011
数字前面的零被保留下来。
发布于 2015-07-03 13:03:16
试试这个:
//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());
}发布于 2015-07-03 13:05:54
这可以通过递归函数调用来解决:
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");
            }
        }
    }
} 发布于 2015-07-03 13:05:32
如果要保留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);
}https://stackoverflow.com/questions/31207301
复制相似问题