I know there are multiple ways of writing code for this type of question, but I'm trying to understand my Professor's way. He wrote a method that takes the value of an integer in an array and assigns it the value of another random integer in the array, i.e "shuffling a deck":
static void shuffle(int[ ] deck) {
//Randomize the order of the elements of deck
//Pick a random card to go in position 0, then position 1, etc.
for(int cardNum=0; cardNum<DECK_SIZE-1; cardNum++){
//pick a random value randomCardNum from cardNum...DECK_SIZE-1
int randomCardNum = cardNum+(int)(Math.random()*(DECK_SIZE-cardNum));
//Swap card and randomCard
.....
What I can't understand is why he would have the for
loop go until DECK_SIZE - 1
. There are 52 cards, and I know that an array's last index is n-1, but the last cardNum
is already not inclusive, so it's going from 0 to 50. I tried taking the -1
out, I get 52 random cards either way.
I'm not sure if it has to do with int randomCardNum
, but this seems right as the equation for randomizing numbers in a specific range is :
Min + (int)(Math.random() + (Max-Min))