将所有大小为 n 的二进制字符串生成为布尔数组的最快方法? [英] Fastest way to generate all binary strings of size n into a boolean array?

查看:28
本文介绍了将所有大小为 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 的二进制字符串生成为布尔数组的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆