Home > Blockchain >  How to create combinations of a Scala queue while preserving order?
How to create combinations of a Scala queue while preserving order?

Time:11-15

I have a Scala queue like this:

import scala.collection.mutable._

val q = Queue(golden, lion, and, golden, lady)

I want to generate slices of this queue like this preserving the order:

golden
golden lion
golden lion and 
golden lion and golden
golden lion and golden lady
lion
lion and 
lion and golden
lion and golden lady
and
and golden
and golden lady
golden
golden lady
lady

I know I can do something like this below, but it is not an efficient solution due to the multiple for loops:

for (i <- 0 to queue.length){
  for (j <- 0 to queue.length){
    val slice = queue.slice(i, j).mkString(" ")
    println(slice)
    }
  }

Does anyone know a more optimized way of doing this? Thanks in advance!

CodePudding user response:

Depends on what you want to "optimize" for. If you're optimizing for brevity & laziness, it's basically

words.tails.flatMap(_.inits)

With filtering of empty lists and a bit more formatting:

List("golden", "lion", "and", "golden", "lady")
  .tails
  .flatMap(_.inits)
  .filter(_.nonEmpty)
  .map(_.mkString(" "))
  .mkString("\n")
golden lion and golden lady
golden lion and golden
golden lion and
golden lion
golden
lion and golden lady
lion and golden
lion and
lion
and golden lady
and golden
and
golden lady
golden
lady

Consider also .flatMap(_.inits.toList.reverse) for the exact same order, if that matters.

  • Related