位置: 首頁 > 計算機 > java語言

Java中shuffle演算法的使用

2016-09-11 java語言

導語:shuffle演算法(洗牌演算法)就是將順序打亂,一個典型的應該就是音樂播放器隨機播放,下面是Java中 shuffle 演算法的使用,一起來學習下吧:

  Fisher–Yates shuffle 基本思想(Knuth shuffle ):

To shuffle an array a of n elements (indices 0..n-1):

for i from n 1 downto 1 do

j ← random integer with 0 ≤ j ≤ i

exchange a[j] and a[i]

 JDK源程式碼如下:

  程式碼如下:

/**

* Moves every element of the list to a random new position in the list.

*

* @param list

* the List to shuffle

*

* @throws UnsupportedOperationException

* when replacing an element in the List is not supported

*/

public static void shuffle(List list) {

shuffle(list, new Random());

標籤:JAVA shuffle 演算法
2017-08-24
2019-12-21
2016-04-17
2014-11-18
2017-02-04
2014-11-25
2016-08-01
2015-11-24
2014-11-20
2016-07-16

Copyright ©2024 才華齋 All Rights Reserved.