Created
July 27, 2011 03:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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