将所有大小为 n 的二进制字符串生成为布尔数组的最快方法?

Fastest way to generate all binary strings of size n into a boolean array?(将所有大小为 n 的二进制字符串生成为布尔数组的最快方法?)
本文介绍了将所有大小为 n 的二进制字符串生成为布尔数组的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

例如,如果我想要所有长度为 3 的二进制字符串,我可以像这样简单地声明它们:

For example, if I wanted all binary strings of length 3 I could simply declare them like this:

boolean[] str1 = {0,0,0};
boolean[] str2 = {0,0,1};
boolean[] str3 = {0,1,0};
boolean[] str4 = {0,1,1};
boolean[] str5 = {1,0,0};
boolean[] str6 = {1,0,1};
boolean[] str7 = {1,1,0};
boolean[] str8 = {1,1,1};

将所有可能的长度为 N 的二进制字符串生成到 布尔数组中的最有效方法是什么?

What is the most efficient way to generate all possibly binary strings of length N into a boolean array?

我不一定需要最有效的方法,只需要一种对我来说相当有效且易于多线程的方法.

I don't necessarily need the most efficient method, just one that's fairly efficient and easy for me to multithread.

我应该注意,如果这很重要,我会将它们全部存储在一个 ArrayList 中.

I should note that I will be storing them all in an ArrayList, if that matters.

推荐答案

这是一些生成真值表的代码...(由于数组大小限制,仅适用于 32 位(您可以将大小变量更改为任意值,并且如果需要,将布尔值存储为 1/0):

Here's some code to generate a truth table... (works for only for 32 bits because of array size limits ( you can change the size variable to whatever and store booleans as 1/0 if you want):

int size = 3;
    int numRows = (int)Math.pow(2, size);
    boolean[][] bools = new boolean[numRows][size];
    for(int i = 0;i<bools.length;i++)
    {
        for(int j = 0; j < bools[i].length; j++)
        {
            int val = bools.length * j + i;
            int ret = (1 & (val >>> j));
            bools[i][j] = ret != 0;
            System.out.print(bools[i][j] + "	");
        }
        System.out.println();
    }

这篇关于将所有大小为 n 的二进制字符串生成为布尔数组的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert integer to zero-padded binary string(将整数转换为零填充的二进制字符串)
How Can I Convert Very Large Decimal Numbers to Binary In Java(如何在 Java 中将非常大的十进制数转换为二进制数)
Check if only one single bit is set within an integer (whatever its position)(检查整数中是否只设置了一个位(无论其位置如何))
Embed a Executable Binary in a shell script(在 shell 脚本中嵌入可执行二进制文件)
why does quot;STRINGquot;.getBytes() work different according to the Operation System(为什么“STRING.getBytes() 的工作方式因操作系统而异)
Convert Byte to binary in Java(在Java中将字节转换为二进制)