2013-04-15 57 views
1

我有一個「代幣」的數組列表。我可以用整數填充它們,沒問題。但是,如果不使用內置列表類,我很難隨機重新排列它們。有什麼建議麼?如何在沒有集合的情況下洗牌ArrayList

TopSpinArray<Integer> al = new TopSpinArray<Integer>(numTokens, spinSize); 

    //fills ArrayList with tokens 
    for(int i = 1; i <= numTokens; i++) { 
     al.add(i); 
    } 
+0

的[Knuth的洗牌](http://en.wikipedia.org/wiki/ Knuth_shuffle#The_modern_algorithm)很容易實現。 – Dukeling

+2

@Dukeling可能是迂腐的,但它實際上被稱爲* Fisher-Yates *算法。 – adrianp

+0

@adrianp作爲迂腐,它[[**也**被稱爲Knuth洗牌]](http://en.wikipedia.org/wiki/Knuth_shuffle)。克努特更容易記住(無論如何對我來說)。 – Dukeling

回答

6

您可以使用以下代碼。

public static void shuffleList(List<Integer> a) { 
    int n = a.size(); 
    Random random = new Random(); 
    random.nextInt(); 
    for (int i = 0; i < n; i++) { 
     int change = i + random.nextInt(n - i); 
     swap(a, i, change); 
    } 
    } 

    private static void swap(List<Integer> a, int i, int change) { 
    int helper = a.get(i); 
    a.set(i, a.get(change)); 
    a.set(change, helper); 
    } 

請注意,這是從下面的鏈接複製

http://www.vogella.com/articles/JavaAlgorithmsShuffle/article.html

希望它可以幫助

1

如果你可以洗牌類(可能因爲不是一個列表:那麼你可以填充一個列表,隨機播放該列表,並在你的班級中添加填充數據:

final List<Integer> tempList = new ArrayList<Integer>(); 


    //fills ArrayList with tokens 
    for(int i = 1; i <= numTokens; i++) { 
     tempList.add(i);    

    } 

    Collections.shuffle(tempList); 

    for(Integer i: tempList) { 
     al.add(i); 
    } 
0

基於@Jabir答案

用於交換任何類型的對象(不只是整數)

public static <T> void shuffleList(List<T> a) { 
    int n = a.size(); 
    for (int i = 0; i < n; i++) { 
     int change = i + Random.nextInt(n - i); 
     swap(a, i, change); 
    } 
    } 

    private static <T> void swap(List<T> a, int i, int change) { 
    T helper = a.get(i); 
    a.set(i, a.get(change)); 
    a.set(change, helper); 
    } 
相關問題