Sha*_*kti 36 for-loop scala list
我有以下列表:
List(a, b, c, d, e)
Run Code Online (Sandbox Code Playgroud)
如何从上面的列表中创建所有可能的组合?
我希望有类似的东西:
a
ab
abc
Run Code Online (Sandbox Code Playgroud)
Kim*_*bel 80
或者您可以使用该subsets方法.您必须首先将列表转换为集合.
scala> List(1,2,3).toSet[Int].subsets.map(_.toList).toList
res9: List[List[Int]] = List(List(), List(1), List(2), List(3), List(1, 2), List(1, 3), List(2, 3), List(1, 2, 3))
Run Code Online (Sandbox Code Playgroud)
pag*_*_5b 33
def combine(in: List[Char]): Seq[String] =
for {
len <- 1 to in.length
combinations <- in combinations len
} yield combinations.mkString
Run Code Online (Sandbox Code Playgroud)
def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el) }
Run Code Online (Sandbox Code Playgroud)
听起来你需要Power Set.
val xs = List( 'a', 'b' , 'c' , 'd' , 'e' )
(1 to xs.length flatMap (x => xs.combinations(x))) map ( x => x.mkString(""))
Run Code Online (Sandbox Code Playgroud)
这应该给你所有由空String连接的组合.