java: card shuffle,

匆匆过客 提交于 2020-01-03 03:23:06

问题


This is a interview-questions. Please give some hints:

Use vector to implement a method, shuffle a deck of Card.

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!
}



}

回答1:


The code for Collections.shuffle() can be found in the source bundle for the JDK or from OpenJDK, but the algorithm is pretty simple (basically the same for a collection as for an array):

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

This works in place so you don't need extra parallel memory. It is known as the Fisher Yates shuffle.




回答2:


Here's what comes to mind :

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;
}

This is dry coded, no testing done.




回答3:


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;
}


来源:https://stackoverflow.com/questions/5205321/java-card-shuffle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!