Skip to content

Instantly share code, notes, and snippets.

@spoertsch
Created October 9, 2013 18:07
Show Gist options
  • Save spoertsch/6905545 to your computer and use it in GitHub Desktop.
Save spoertsch/6905545 to your computer and use it in GitHub Desktop.
IPSWAYS Scala Meetup - Creating unique Pairs of players using for expression
val players = List("Timo", "Jan", "Lothar", "Sven", "Danny")
//> players : List[String] = List(Timo, Jan, Lothar, Sven, Danny)
val playerPairs = for {
p1 <- players
p2 <- players
if p1 != p2
} yield (p1, p2)
//> playerPairs : List[(String, String)] = List((Timo,Jan), (Timo,Lothar), (Tim
//| o,Sven), (Timo,Danny), (Jan,Timo), (Jan,Lothar), (Jan,Sven), (Jan,Danny), (L
//| othar,Timo), (Lothar,Jan), (Lothar,Sven), (Lothar,Danny), (Sven,Timo), (Sven
//| ,Jan), (Sven,Lothar), (Sven,Danny), (Danny,Timo), (Danny,Jan), (Danny,Lothar
//| ), (Danny,Sven))
playerPairs.size
//> res0: Int = 20
val playerPairs2 = for {
p1 <- players
p2 <- players.dropWhile(_ != p1)
if p1 != p2
} yield (p1, p2)
//> playerPairs2 : List[(String, String)] = List((Timo,Jan), (Timo,Lothar), (Ti
//| mo,Sven), (Timo,Danny), (Jan,Lothar), (Jan,Sven), (Jan,Danny), (Lothar,Sven)
//| , (Lothar,Danny), (Sven,Danny))
playerPairs2.size
//> res1: Int = 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment