I need to construct all possible binary representations from a string containing only the characters 0
, 1
, and V
(the wildcard). The string may be of any length (over 1000 characters) though the number of wildcards is less than 20.
For example, for the input V1V
the output would be [010, 011, 110, 111]
My current implementation works but overflows the stack with a modest number of wildcards. The code is running here and shown below.
def permutts
permutts =
{
if (!it.contains('V'))
return [it]
def target = it
def res = []
['0', '1'].each
{
def s = target.replaceFirst(~/V/, it)
if (s.contains('V'))
{
res += permutts(s)
}
else
{
res << s
}
}
res
}
println permutts('V1V')
I've attempted to follow some of the examples of using trampoline()
but I'm not even sure if that's the right approach. The API says, "...the function is supposed to perform one step of the calculation..." but each step performs two actions: substituting in 0
and 1
for V
.
Here's one of my attempts, which can be run here.
def permutts
permutts =
{ it, res = [] ->
println "entering with " + it + ", res=" + res
if (it.contains('V'))
{
def s = it.replaceFirst(~/V/, '1')
permutts.trampoline(s, res)
s = it.replaceFirst(~/V/, '0')
permutts.trampoline(s, res)
}
else
{
res << it
}
}.trampoline()
println permutts('VV')
The output is:
entering with VV, res=[]
entering with 0V, res=[]
entering with 00, res=[]
[00]
At least it's doing something but I don't understand why it doesn't keep going. Can anyone explain what I'm doing wrong or suggest a different way to tackle this problem?