Given a pattern , we need to generate all possible binary numbers by filling the missing places in the pattern by 0 and 1.
E.g. Pattern = "x1x";
Output = [010, 110, 011, 111]
I solved it by creating a method calculate
.
public static List<String> calculate(String input, int currentIndex) {
List<String> result = new ArrayList<String>();
if(currentIndex > input.length()-1) {
result.add("");
return result;
}
for(String fragment: calculate(input, currentIndex + 1)) {
if(input.charAt(currentIndex)=='x') {
result.add('0' + fragment);
result.add('1' + fragment);
}
else {
result.add(input.charAt(currentIndex) + fragment);
}
}
return result;
}
Is there some way in which we can leverage the given pattern and design a much Faster and/or cleaner solution. I already know that non-recursive solution will be better. Java 8 features are also welcome.
On reflection, using recursion and a call back is much more efficient way of doing this. Note: this creates very few objects (possibly 3 regardless of the number of results).
To add this to a list you can do
You can;
x
s. This is the number of bits you need to iterate over.x
.x
with the provided bit pattern.