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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)