0

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.

2
  • What is the output of genBinary(3)? What would be the output of genBinary(2)? Commented Jan 19, 2016 at 9:58
  • @0__ I've added and example output. Commented Jan 19, 2016 at 10:23

1 Answer 1

4

Here's one way you could do it with Streams:

val bss: Stream[Vector[List[Boolean]]] = 
    Vector(List.empty) #:: bss.map(bs => bs.map(true :: _) ++ bs.map(false :: _))

bss(3).mkString("\n")
//res1: String =
//List(true, true, true)
//List(true, true, false)
//List(true, false, true)
//List(true, false, false)
//List(false, true, true)
//List(false, true, false)
//List(false, false, true)
//List(false, false, false)

bss(4).mkString("\n")
//res2: String =
//List(true, true, true, true)
//List(true, true, true, false)
//List(true, true, false, true)
//List(true, true, false, false)
//List(true, false, true, true)
//List(true, false, true, false)
//List(true, false, false, true)
//List(true, false, false, false)
//List(false, true, true, true)
//List(false, true, true, false)
//List(false, true, false, true)
//List(false, true, false, false)
//List(false, false, true, true)
//List(false, false, true, false)
//List(false, false, false, true)
//List(false, false, false, false)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I came up with a code that probably works (I posted it bellow), but yours is much more concise and feels like it adheres to the language more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.