How to get pairwise collection combinations ignoring order?

Suppose I have a collection (let the set be used):

scala> val x = Set(1, 2, 3)
x: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

I can get all paired combinations with the following code:

scala> for {
     | a <- x
     | b <- x
     | if a != b
     | } yield (a, b)
res9: scala.collection.immutable.Set[(Int, Int)] = Set((3,1), (3,2), (1,3), (2,3), (1,2), (2,1))

The problem is that I only want to get all paired combinations where the order is ignored (therefore the combination is (1, 2)equivalent (2, 1)). Therefore, I would like to return Set((3, 1), (3, 2), (1, 2)).

Do not assume that the elements of the collection will be intact. They can be arbitrary types.

Any ideas?

Edit: Python itertools.combinationsperforms the exact functions I'm looking for. I just need an idiomatic way to do this in Scala :)

+4
source share
2 answers

Scala combinations, Seq, Set. Seq, Iterator[Seq[Int]]:

x.toSeq.combinations(2)

, map {case Seq(a,b) => (a,b)} .

+11

, :

scala> val s3 = for {
     | a <- x
     | b <- x
     | if(a != b)
     | } yield ( Set(a,b))
s3: scala.collection.immutable.Set[scala.collection.immutable.Set[Int]] = Set(Set(1, 2), Set(1, 3), Set(2, 3))
+3

All Articles