简体   繁体   中英

How to generate rules from a string values in scala?

I want to make rules from strings. for example, My strings are:

Ball Cat Egg
Cat Egg
Apple Cat
Ball Egg
Ball Cat

I want the rules as,

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

EDIT Here is the code for new question:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM