list 如何从列表的元素创建所有可能的组合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13109720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:55:00  来源:igfitidea点击:

How to create all possible combinations from the elements of a list?

listscalafor-loop

提问by Shakti

I have the following list:

我有以下清单:

List(a, b, c, d, e)

How to create all possible combinations from the above list?

如何从上面的列表中创建所有可能的组合?

I expect something like:

我期待这样的事情:

a
ab
abc 

回答by Kim Stebel

Or you could use the subsetsmethod. You'll have to convert your list to a set first though.

或者你可以使用该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))

回答by pagoda_5b

def combine(in: List[Char]): Seq[String] = 
    for {
        len <- 1 to in.length
        combinations <- in combinations len
    } yield combinations.mkString 

回答by Science_Fiction

def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el) }

Sounds like you need the Power set.

听起来您需要Power set

回答by Santosh Gokak

val xs = List( 'a', 'b' , 'c' , 'd' , 'e' )
(1 to xs.length flatMap (x => xs.combinations(x))) map ( x => x.mkString(""))

This should give you all the combination concatenated by empty String.

这应该为您提供由空字符串连接的所有组合。