Scala嵌套循环产生

时间:2014-05-12 19:47:02

标签: scala loops for-loop

我想知道在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 {
       // ??
  }

并且在输出中我希望有一个Seq of Pots,其中放置了所有可能的鲜花组合。因此,在下面的示例中,输出应为:

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")))
)

任何想法?

2 个答案:

答案 0 :(得分:2)

这是你想要的吗?

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)))

答案 1 :(得分:0)

我想通了,现在这个解决方案似乎有效:

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

val pots: Seq[Pot] = res.sliding(flowers.size).map(l => Pot(width, height, l.map(f => FlowerInPot(f._1, f._2, f._3)))).toList