Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala generate unique pairs from list

Input :

val list = List(1, 2, 3, 4)

Desired output :

Iterator((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))

This code works :

for (cur1 <- 0 until list.size; cur2 <- (cur1 + 1) until list.size)
  yield (list(cur1), list(cur2))

but it not seems optimal, is there any better way of doing it ?

like image 723
Co_42 Avatar asked Oct 29 '14 10:10

Co_42


1 Answers

There's a .combinations method built-in:

scala> List(1,2,3,4).combinations(2).toList
res0: List[List[Int]] = List(List(1, 2), List(1, 3), List(1, 4), List(2, 3), List(2, 4), List(3, 4))

It returns an Iterator, but I added .toList just for the purpose of printing the result. If you want your results in tuple form, you can do:

scala> List(1,2,3,4).combinations(2).map{ case Seq(x, y) => (x, y) }.toList
res1: List[(Int, Int)] = List((1,2), (1,3), (1,4), (2,3), (2,4), (3,4))

You mentioned uniqueness as well, so you could apply .distinct to your input list uniqueness isn't a precondition of your function, because .combination will not deduplicate for you.

like image 100
acjay Avatar answered Oct 15 '22 14:10

acjay