I am trying to think of an algorithm where I can create number of possible binary combinations for my inference engine implementation
in short if input file to my program has 4 distinct variables my program should be able to generate
0000 0001 0010 . . . 1111
combinations.... So far my approach to this problem is as below which is just a thought as it is hard coded at the moment... Basically I need algorithm to generate this for any given number of variable "n".
My Code so far...
public class TTAlgorithm {
public static void main(String[] args) {
Integer j = new Integer(10);
for (int i = 0; i < 4096; i++) {
if (j.toBinaryString(i).length() == 1) {
System.out.println("0000000000" + j.toBinaryString(i));
}
if (j.toBinaryString(i).length() == 2) {
System.out.println("000000000" + j.toBinaryString(i));
}
if (j.toBinaryString(i).length() == 3) {
System.out.println("00000000" + j.toBinaryString(i));
}
if (j.toBinaryString(i).length() == 4) {
System.out.println("0000000" + j.toBinaryString(i));
开发者_JAVA技巧 }
if (j.toBinaryString(i).length() == 5) {
System.out.println("000000" + j.toBinaryString(i));
}
if (j.toBinaryString(i).length() == 6) {
System.out.println("00000" + j.toBinaryString(i));
}
if (j.toBinaryString(i).length() == 7) {
System.out.println("0000" + j.toBinaryString(i));
}
if (j.toBinaryString(i).length() == 8) {
System.out.println("000" + j.toBinaryString(i));
}
if (j.toBinaryString(i).length() == 9) {
System.out.println("00" + j.toBinaryString(i));
}
if (j.toBinaryString(i).length() == 10) {
System.out.println("0" + j.toBinaryString(i));
}
if (j.toBinaryString(i).length() == 11) {
System.out.println("" + j.toBinaryString(i));
}
}
}
}
Thanks for any help....
This should work...
public static void main(String[] args) throws Exception {
int count = 0;
int stringSize = 4;
int maxValue= (int)Math.pow(2, stringSize);
while(count < maxValue) {
String binaryString = Integer.toBinaryString(count);
while(binaryString.length() < stringSize) {
binaryString = "0" + binaryString;
}
System.out.println(binaryString);
count++;
}
}
Output is...
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
Put that in a method and have the method take an argument "stringSize" or whatever you want to call it.
See Incrementing array values - Arduino for an very easy solution.
精彩评论