首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >生成二进制序列

生成二进制序列
EN

Stack Overflow用户
提问于 2015-07-03 12:49:03
回答 4查看 815关注 0票数 2

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

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

1100 1010 1001 0110 0101 0011

数字前面的零被保留下来。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-07-03 13:03:16

试试这个:

代码语言:javascript
运行
复制
//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());
}
票数 1
EN

Stack Overflow用户

发布于 2015-07-03 13:05:54

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

代码语言:javascript
运行
复制
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");
            }
        }
    }


} 
票数 3
EN

Stack Overflow用户

发布于 2015-07-03 13:05:32

如果要保留0,只需添加填充:

代码语言:javascript
运行
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31207301

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档