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

11,120

Solution 1

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.

Solution 2

Random is "shuffling" the Set; it just has no visible effect since sets do not have an order. The REPL happens to print the shuffled sets the same way every time:

scala> Set(1,2,3,4,5) 
res29: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)

scala> Set(5,4,3,2,1)
res30: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)

scala> util.Random.shuffle(res30)
res31: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)
Share:
11,120
k r
Author by

k r

Updated on June 03, 2022

Comments

  • k r
    k r almost 2 years
     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 ?