[英]How to generate rules from a string values in scala?
我想根據字符串制定規則。 例如,我的字符串是:
Ball Cat Egg
Cat Egg
Apple Cat
Ball Egg
Ball Cat
我想要規則,
Ball -> Cat Egg
Cat -> Ball Egg
Egg -> Ball Cat
Ball Cat -> Egg
Cat Egg -> Ball
Ball Egg -> Cat
Cat -> Egg
Egg -> Cat
Apple -> Cat
Cat -> Apple
Ball -> Egg
Egg -> Ball
Ball -> Cat
Cat -> Ball
scala> val strs = Seq("BCE", "CE", "AC", "BE", "BC")
strs: Seq[String] = List(BCE, CE, AC, BE, BC)
scala> val rules = for(s <- strs;i <- 1 to s.size-1;p <- s combinations i) yield p -> s.diff(p)
rules: Seq[(String, String)] =
List((B,CE),
(C,BE),
(E,BC),
(BC,E),
(BE,C),
(CE,B),
(C,E),
(E,C),
(A,C),
(C,A),
(B,E),
(E,B),
(B,C),
(C,B))
編輯這是新問題的代碼:
scala> case class Rule(src: Seq[String], dst: Seq[String]) {
| override def toString = s"${src.mkString(" ")} -> ${dst.mkString(" ")}"
| }
defined class Rule
scala> val strs = Seq("Ball Cat Egg", "Cat Egg", "Apple Cat", "Ball Egg", "Ball Cat")
strs: Seq[String] = List(Ball Cat Egg, Cat Egg, Apple Cat, Ball Egg, Ball Cat)
scala> val rules = for(s <- strs;l = s.split(" ");i <- 1 to l.size-1;p <- l combinations i)
yield Rule(p, l diff p)
rules: Seq[Rule] = List(Ball -> Cat Egg, Cat -> Ball Egg, Egg -> Ball Cat,
Ball Cat -> Egg, Ball Egg -> Cat, Cat Egg -> Ball,
Cat -> Egg, Egg -> Cat, Apple -> Cat, Cat -> Apple,
Ball -> Egg, Egg -> Ball, Ball -> Cat, Cat -> Ball)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.