0

I have two arrays (representing a deck of cards), one filled with the values 1-52, and another filled with nothing. I want to take the position randomly from the first array and take that object and put it into the next spot available in the randomized array. I have this so far:

var shufdeck = new Array();
while(sufdeck.length < 52)
{
    i = Math.floor(Math.random()*52);
    //shufdeck[0] = deck[i] etc.
}

I'm not sure if I should be using splice or something else to take it out of the first array and put it into the second. If possible shufdeck[] should be filled and deck[] would be empty.

How can I shuffle an array?

Community
  • 1
  • 1
user3413170
  • 251
  • 1
  • 3
  • 13
  • 2
    http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle – Matt Mar 13 '14 at 00:12
  • Do you care whether the original deck[] is empty at the end, or do you only need shufdeck[] to be a shuffled version of deck[]? – gpcz Mar 13 '14 at 00:14
  • I only need shufdeck[] to be filled. the original deck[] should be empty if possible. – user3413170 Mar 13 '14 at 00:15
  • 1
    Check out http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – gpcz Mar 13 '14 at 00:17
  • Thanks, I found http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript?lq=1 to be more helpful! – user3413170 Mar 13 '14 at 00:21

1 Answers1

2

Yes, you should splice out the chosen card, so:

var shuffledDeck = [];

while (deck.length) {
  shuffledDeck.push(deck.splice(Math.random()*deck.length | 0, 1)[0]);
}

or to be a little more efficient:

var i = deck.length;
while (i) {
  shuffledDeck.push(deck.splice(Math.random()*i-- | 0, 1)[0]);
}

Note that this will destroy deck. If you don't want that, copy it first:

var deckToShuffle = deck.slice();
RobG
  • 142,382
  • 31
  • 172
  • 209