使用scala.util.Random在Set vs List上进行shuffle的行为

时间:2012-06-28 19:14:31

标签: list scala random set shuffle

 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)

所以shuffle可以处理列表就好了,但没有设置? 洗不了套? 为什么res10 == res11 == res12?

2 个答案:

答案 0 :(得分:20)

Scala的集合没有排序(就像数学集合一样)。它们是可迭代的,但是你不能依赖于你将获得项目的顺序。许多集合的实现将以相同的顺序迭代相同的元素 - 即。,

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

这解释了你在这里看到的效果。你永远不应该依赖于此,但是可能存在一个完美的有效Set实现,而上述实现并不成立。

答案 1 :(得分:2)

随机是“洗牌”Set;它只是没有明显的效果,因为集合没有订单。 REPL碰巧每次都以相同的方式打印混洗集:

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)