2011-03-05 179 views
1

這是一個面試問題。請提供一些提示:java:卡洗牌,

使用vector實現一個方法,洗牌一副牌。

public class Card { 
    private int value; 
    Card(int v) { 
     value = v; 
     } 

    public void print(){ 
     System.out.print(value+";"); 
    } 
} 



public class DeckShuffle { 

    private final int num; 
    Vector<Card> deck = new Vector<Card>(); 

// implement this shuffle function. DO NOT USE Collections.shuffle() !! 
public void shuffle(){ 
// your code goes here! 
} 



} 

回答

4

Collections.shuffle()的代碼可以在用於JDK或從OpenJDK的源包被發現,但算法是相當簡單的(基本上相同的對的集合作爲一個數組):

given a[] 
for i <- 0..a.length-2 
    rnd_index <- random(i, a.length) #inclusive, exclusive 
    swap a[i] and a[rnd_index] 
next 

該作品因此您不需要額外的並行內存。它被稱爲Fisher Yates shuffle

0

這裏是想到什麼:

public void shuffle() { 
    Vector<Card> v = new Vector<Card>(deck.size()); 
    int size = deck.size(); 
    for(int i = 0; i < size; i++) { 
     int index = Math.random() * deck.size(); 
     Card c = deck.remove(index); 
     v.add(c); 
    } 
    deck = v; 
} 

這是乾燥的編碼,沒有測試來完成。

-2
void Shuffle() 
{ 
    int n= deck.size(); 
    Vector<Card> v = new Vector<Card>(n); 


    for (int i = 0; i < n; i++) { 
    int j = (int)((i-1) * Math.random())+ 1; 
    if (i != j) { 
     swap(cards, i, j); 
    } 
    } 

    deck = v; 
} 
+2

http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html – Flexo 2011-10-02 17:34:39