使用 scala.util.Random 在 Set 与 List 上随机播放的行为
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11251380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Behavior of shuffle on Set vs List using scala.util.Random
提问by k r
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 ?
所以 shuffle 可以很好地处理 Lists ,但不能处理 Sets ?不能洗牌吗?为什么 res10 == res11 == res12 ?
回答by Travis Brown
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 的集合不是有序的(就像数学集合一样)。然而,它们是可迭代的——你不能依赖获取元素的顺序。集合的许多实现会以相同的顺序迭代相同的元素——即,
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 Setimplementation for which the above wouldn't hold.
这解释了你在这里看到的效果。但是,您永远不应该依赖于此 - 可能有一个完美的有效Set实现,但上面的内容不成立。
回答by retrospectacus
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:
Random 正在“洗牌” 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)

