Skip to content

Instantly share code, notes, and snippets.

@anupsavvy
Created July 27, 2011 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anupsavvy/1108633 to your computer and use it in GitHub Desktop.
Save anupsavvy/1108633 to your computer and use it in GitHub Desktop.
Write a method to shuffle a deck of cards. It must be a perfect shuffle – in other words, each 52! permutations of the deck has to be equally likely. Assume that you are given a random number generator which is perfect.
public class Puzzle {
public static int[] shuffleCards(int[] cards){
if(cards == null || cards.length==1 || cards.length==0){
return cards;
}
int cardNumber,hold;
for(int i =0; i < cards.length; i++){
cardNumber = (int)(Math.random()*(cards.length-i)) + 1;
hold = cards[cardNumber];
cards[cardNumber] = cards[i];
cards[i] = hold;
}
return cards;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment