問(wèn)題描述
例如,如果我想要所有長(zhǎng)度為 3 的二進(jìn)制字符串,我可以像這樣簡(jiǎn)單地聲明它們:
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};
將所有可能的長(zhǎng)度為 N 的二進(jìn)制字符串生成到 布爾數(shù)組中的最有效方法是什么?
What is the most efficient way to generate all possibly binary strings of length N into a boolean array?
我不一定需要最有效的方法,只需要一種對(duì)我來(lái)說(shuō)相當(dāng)有效且易于多線程的方法.
I don't necessarily need the most efficient method, just one that's fairly efficient and easy for me to multithread.
我應(yīng)該注意,如果這很重要,我會(huì)將它們?nèi)看鎯?chǔ)在一個(gè) ArrayList 中.
I should note that I will be storing them all in an ArrayList, if that matters.
推薦答案
這是一些生成真值表的代碼...(由于數(shù)組大小限制,僅適用于 32 位(您可以將大小變量更改為任意值,并且如果需要,將布爾值存儲(chǔ)為 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();
}
這篇關(guān)于將所有大小為 n 的二進(jìn)制字符串生成為布爾數(shù)組的最快方法?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!