创建大小为n的布尔数组的所有可能的方法是什么? [英] Creating all possible ways of a boolean array of size n?
问题描述
我需要能够创建一个组合的布尔数组并运行它通过一个程序,看它是否工作。如果没有,那么我处置,进入下一个组合。我的问题是,我不知道如何创建这个数组,因为n可以等于1-1000的任何地方。所以我打算用Integer.toBinaryString但将由于其过大时,它得到过去32不起作用。
任何帮助将不胜感激。
I need to be able to create a boolean array of one combination and run it through a program to see if it works. If not then I dispose of it and go to the next combination. My issue is that I don't know how to create this array because n can be equal anywhere from 1-1000. So I was planning on using Integer.toBinaryString but that won't work due to its too big when it gets to past 32. Any help would be greatful.
谢谢!
推荐答案
我发现另一个回答您的问题<一href=\"http://stackoverflow.com/questions/10923601/java-generator-of-trues-falses-combinations-by-giving-the-number-n\">SO问题,我已经适应它你:
I've found the answer to your problem on another SO question, and I've adapted it for you:
public class Foo {
public static void main(String[] args) {
final int n = 3;
for (int i = 0; i < Math.pow(2, n); i++) {
String bin = Integer.toBinaryString(i);
while (bin.length() < n)
bin = "0" + bin;
char[] chars = bin.toCharArray();
boolean[] boolArray = new boolean[n];
for (int j = 0; j < chars.length; j++) {
boolArray[j] = chars[j] == '0' ? true : false;
}
System.out.println(Arrays.toString(boolArray));
}
}
}
会产生:
[true, true, true]
[true, true, false]
[true, false, true]
[true, false, false]
[false, true, true]
[false, true, false]
[false, false, true]
[false, false, false]
测试,这会为高价值工作 N
,如10000等。
这篇关于创建大小为n的布尔数组的所有可能的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!