Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala nested loops yield

I wonder if there is a simple way to do something like this in scala:

case class Pot(width: Int, height: Int, flowers: Seq[FlowerInPot])
case class FlowerInPot(x: Int, y: Int, flower: String)

val flowers = Seq("tulip", "rose")
val height = 3
val width = 3

val res =
  for (flower <- flowers;
       h <- 0 to height;
       w <- 0 to width) yield {
       // ??
  }

and at an output I'd like to have a Seq of Pots with all possible combinations of flowers placed in it. So in following example, the output should be:

Seq(
  Pot(3, 3, Seq(FlowerInPot(0, 0, "tulip"), FlowerInPot(0, 1, "rose"))),
  Pot(3, 3, Seq(FlowerInPot(0, 0, "tulip"), FlowerInPot(0, 2, "rose"))),
  Pot(3, 3, Seq(FlowerInPot(0, 0, "tulip"), FlowerInPot(1, 0, "rose"))),
  Pot(3, 3, Seq(FlowerInPot(0, 0, "tulip"), FlowerInPot(1, 1, "rose"))),
  ...
  Pot(3, 3, Seq(FlowerInPot(2, 2, "tulip"), FlowerInPot(2, 1, "rose")))
)

any ideas?

like image 607
gysyky Avatar asked Mar 20 '26 17:03

gysyky


1 Answers

Is this what you want?

case class FlowerInPot(x: Int, y: Int, flower: String)
case class Pot(width: Int, height: Int, flowers: Seq[FlowerInPot])

val x, y = 0
val flowers = Seq("tulip", "rose")
val height = 3
val width = 3

val res = for {
  h <- 0 to height
  w <- 0 to width
} yield Pot(height, width, flowers.map(flower => FlowerInPot(w, h, flower)))
like image 154
Ionuț G. Stan Avatar answered Mar 23 '26 06:03

Ionuț G. Stan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!