While recursion is undoubtedly more elegant, it is also easy to write a function that takes a pattern and binary string and creates the next binary string according to the pattern. Then you just need to start with the line created by changing all x in the template to 0 s and repeat using successors until you reach a line that does not have it.
To find a successor for the string specified by the pattern, iterate backward along both the string and the pattern. In each character position:
- If the pattern character is
x :- if the string character is
1 , change it to 0 . - if the string character is
0 , change it to 1 and return True.
- Otherwise, the pattern character must match the string character. In any case, continue the cycle.
If the loop does not end with return , then there is no successor, and the function should return False. At this point, the string is initialized to its initial value.
Iterating back over a pattern / line results in values ββin lexicographical order. If you donβt need the order in which the values ββare produced, the code may be a little easier if you go ahead.
In Java, strings are immutable, so you cannot just mutate the input string. If you need to create a copy of a string, you cannot just go back to where the above algorithm indicates a return; you need to fill out a copy. If you use StringBuilder, then it will definitely be easier to work backwards.
source share