user3370773
user3370773

Reputation: 455

Calculate all combinations of list when order doesn't matter

I have a List[String], and i want to create a list of all possible pair combinations when order doesn't matter, i.e. ("a", "b") and ("b", "a") are the same combination.

For example:

val List = ("a", "b", "c")

The result I expect is:

List[List[String]] = List(List(a, b), List(a, c), List(b, c)) 

Thanks

Upvotes: 0

Views: 600

Answers (2)

Brian
Brian

Reputation: 20285

The combinations method does this. Your List value is actually a tuple though so define as a List as I did below.

scala> val list = List("a","b","c")
list: List[String] = List(a, b, c)

scala> list.combinations(2)
res0: Iterator[List[String]] = non-empty iterator

scala> list.combinations(2).toList
res1: List[List[String]] = List(List(a, b), List(a, c), List(b, c))

Upvotes: 1

Michael Zajac
Michael Zajac

Reputation: 55569

A quick look at the collections API, and you'd get this:

List("a", "b", "c").combinations(2).toList

Upvotes: 0

Related Questions