我想知道在 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")))
)
有什么想法吗?
最佳答案
这是你想要的吗?
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)))
关于Scala 嵌套循环产量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23617576/