Fastest way to generate all binary strings of size n into a boolean array?(将所有大小为 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 的二进制字符串生成为布尔数组的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将所有大小为 n 的二进制字符串生成为布尔数组
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
