Reputation: 7634
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!
}
}
Upvotes: 1
Views: 5536
Reputation: 1
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;
}
Upvotes: -2
Reputation: 81154
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.
Upvotes: 4
Reputation: 26607
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.
Upvotes: 0