Java:真实的生成器通过给出数字n来计算false的组合 [英] Java: Generator of true's & false's combinations by giving the number N;
问题描述
我尽可能地简化任务,以便将其应用到我的算法中.
I tied to simplify the task as much as possible, so I could apply it to my algorithm.
这是数学家和程序员面临的挑战:
And here is the challenge for mathematicians and programmers:
我需要创建一个方法来传递参数 int n:
I need to create a method where I pass parameter int n:
public void optionality_generator(int n){
//some kind of loops, or recursions...to make it workable
System.out.println("current combination: ...");
}
输出应显示真假的所有可能组合.
The output should show all possible combinations of true's and false's.
这里是 N=1 的例子;N=2;N=3;N=4;N=5,其中 x=false 和 0=true;请注意,空分隔线只是为了让您更容易识别模式.希望我包含了所有可能的组合):
Here is examples where N=1; N=2; N=3; N=4; N=5 where x=false and 0=true; Please note, empty break lines is just for you to recognise easier the patterns. Hopefully, I included all possible combinations):
Combination of 1:
0
x
Combination of 2:
00
x0
0x
xx
Combination of 3:
000
X00
0X0
00X
XX0
0XX
XXX
Combination of 4:
0000
X000
0X00
00X0
000X
XX00
X0X0
X00X
0XX0
0X0X
00XX
XXX0
XX0X
X0XX
0XXX
XXXX
Combination of 5:
00000
X0000
0X000
00X00
000X0
0000X
XX000
X0X00
X00X0
X000X
X0X00
X00X0
X000X
0XX00
0X0X0
0X00X
00XX0
00X0X
000XX
XXX00
XX0X0
XX00X
X0XX0
X0X0X
X00XX
0XXX0
0XX0X
00XXX
XXXX0
XXX0X
XX0XX
X0XXX
0XXXX
XXXXX
另外,如果你看到输出,这里是我识别的模式,所有组合都倒转了一半(例如第一个组合是 00000,最后一个将是 XXXXX,第二个 X0000,在最后一个之前的一个将是 0XXXX 等...).也许,这种模式将有助于使整个算法更高效,对此不确定.提前谢谢你!
Also, If you see the output, here is the pattern I recognized, that all combinations are inverted on half (e.g first combination is 00000 last one will be XXXXX, second one X0000, one before the last one will be 0XXXX etc..). Maybe, this pattern will help to make the whole algorithm more efficient, not sure about this. Thank you in advance!
推荐答案
以下是一种仅使用 Java API 的非常基本的方法:
Here is a really basic way using only Java APIs:
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;
System.out.println(bin);
}
结果:
000
001
010
011
100
101
110
111
当然,您可以将 n
设置为您喜欢的任何值.并且,根据这个结果,您可以从字符串中选择第 n
个字符作为真/假.
Of course, you can set n
to whatever you like. And, with this result, you can pick the n
th character from the string as true/false.
如果只需要检查某个位是否为真,则不需要将其转换为字符串.这只是为了说明输出值.
If you only need to check if a bit is true, you don't need to convert it to a string. This is just to illustrate the output values.
这篇关于Java:真实的生成器通过给出数字n来计算false的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!