Behavior of shuffle on Set vs List using scala.util.Random

k r picture k r · Jun 28, 2012 · Viewed 11k times · Source
 scala> Random.shuffle((1 to 10).toSet)
 res10: scala.collection.immutable.Set[Int] = Set(5, 10, 1, 6, 9, 2, 7, 3, 8, 4)

 scala> Random.shuffle((1 to 10).toSet)
 res11: scala.collection.immutable.Set[Int] = Set(5, 10, 1, 6, 9, 2, 7, 3, 8, 4)

 scala> Random.shuffle((1 to 10).toSet)
 res12: scala.collection.immutable.Set[Int] = Set(5, 10, 1, 6, 9, 2, 7, 3, 8, 4)

 scala> Random.shuffle((1 to 10).toList)
 res13: List[Int] = List(3, 9, 8, 5, 7, 6, 10, 2, 1, 4)

 scala> Random.shuffle((1 to 10).toList)
 res14: List[Int] = List(5, 10, 2, 9, 4, 7, 8, 6, 1, 3)

 scala> Random.shuffle((1 to 10).toList)
 res15: List[Int] = List(5, 9, 10, 6, 8, 3, 4, 1, 7, 2)

So shuffle can handle Lists just fine, but not sets ? Can't sets be shuffled ? Why is res10 == res11 == res12 ?

Answer

Travis Brown picture Travis Brown · Jun 28, 2012

Scala's sets aren't ordered (just like the mathematical ones). They are iterable, however—you just can't rely on the order that you'll get the items in. Many implementations of sets will iterate the same elements in the same order—i.e.,

scala> Set(1, 2, 3, 4, 5).toList == Set(5, 4, 3, 2, 1).toList
res0: Boolean = true

Which explains the effect you're seeing here. You should never rely on this, though—there could be a perfect valid Set implementation for which the above wouldn't hold.