I want to generate all binary sequences of a given length, however I want it done lazily, so as not to overload memory.
As an example of what i want, I provide a Python code, that does exactly what I want:
def nextBinary(i, seq):
b = seq[:i] + [1] + seq[i + 1:]
yield b
if i + 1 < len(seq):
for nextSeq in nextBinary(i + 1, seq):
yield nextSeq
for nextSeq in nextBinary(i + 1, b):
yield nextSeq
def genBinary(length):
start = [0 for i in range(length)]
yield start
for seq in nextBinary(0, start):
yield seq
Now the genBinary returns a generator object which I can use like this:
for seq in genBinary(2):
print(seq)
# [0, 0]
# [1, 0]
# [0, 1]
# [1, 1]
for seq in genBinary(3):
print(seq)
# [0, 0, 0]
# [1, 0, 0]
# [0, 1, 0]
# [0, 0, 1]
# [0, 1, 1]
# [1, 1, 0]
# [1, 0, 1]
# [1, 1, 1]
How would I code something equivalent in Scala? I suspect it might be somehow doable with Streams or maybe continuations.
genBinary(3)? What would be the output ofgenBinary(2)?