Simmy
Simmy

Reputation: 11

How do I take data from one array, pick half at random without the same card being picked twice, then move them to another array?

I'm trying to make a basic/simple War card game, and I'm working on the Javascript part. I'm stuck on how to take half of the card values at random, and not picking the same one over and over, to move them into another array to simulate shuffling (picking at random) and moving them into a second array (simulating dealing more or less).

var DeckofCards = new Array('2D', '2H', '2S', '2C', '3D', '3H', '3S', '3C', '4D', '4H', '4S', '4C',
                    '5D', '5H', '5S', '5C', '6D', '6H', '6S', '6C', '7D', '7H', '7S', '7C',
                    '8D', '8H', '8S', '8C', '9D', '9H', '9S', '9C', '10D', '10H', '10S', '10C',
                    '11D', '11H', '11S', '11C', '12D', '12H', '12S', '12C',
                    '13D', '13H', '13S', '13C', '14D', '14H', '14S', '14C')

How would I write the code to do everything I want right now? Also, please try to keep your answer code as simple as possible so I can understand it a lot more easily.

Upvotes: 1

Views: 47

Answers (1)

gurvinder372
gurvinder372

Reputation: 68413

Using the shuffling method given here, try this

var DeckofCards = new Array('2D', '2H', '2S', '2C', '3D', '3H', '3S', '3C', '4D', '4H', '4S', '4C', '5D', '5H', '5S', '5C', '6D', '6H', '6S', '6C', '7D', '7H', '7S', '7C', '8D', '8H', '8S', '8C', '9D', '9H', '9S', '9C', '10D', '10H', '10S', '10C', '11D', '11H', '11S', '11C', '12D', '12H', '12S', '12C', '13D', '13H', '13S', '13C', '14D', '14H', '14S', '14C');

function shuffle(array) 
{
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) 
  {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var output = shuffle(DeckofCards).slice(DeckofCards.length/2);
console.log(output);

Upvotes: 1

Related Questions