maks1m
BAN USERRecently started learning Java :)
After nine years of being a programmer decided to learn java.
Code in Java
/**
* Here is my algorithm without recursion.
* It works faster and eats much less memory comparing to recursion.
* The idea is that values 0 or 1 could be a bits of a number.
* So we have to count symbol '?' and find a number of all possible combinations.
* Combinations quantity is 2^(quantity of '?').
* Then we make a loop and get a value of each bit for every number from loop.
* Easy :)
* Sorry for my english.
*/
public class Combinations {
public static void main(String[] args) {
String test = "a?b?c?d?";
generator(test);
}
private static void generator(String str) {
StringBuilder strB = new StringBuilder();
boolean lastIsQMark = str.substring(str.length() - 1).equals("?");
int bit;
String arr[] = str.split("\\?");
int bitsCount = arr.length - (lastIsQMark ? 0 : 1);
int combinations = (int) Math.pow(2, arr.length - (lastIsQMark ? 0 : 1));
for (int i = 0; i < combinations; i++) {
for (int j = 0; j < bitsCount; j++) {
bit = (i >> bitsCount - j - 1) & 1;
strB.append(arr[j]);
strB.append(bit);
}
if (!lastIsQMark) {
strB.append(arr[bitsCount]);
}
System.out.println(strB.toString());
strB.delete(0, strB.length());
}
}
}
here is corrected variant of your algorithm
- maks1m June 16, 2014