8

I'm trying to create a JavaScript card game and want to pick 5 cards without repetition:

var colors = ["hearts", "spades", "diamonds", "clubs" ];
var values = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

color = colors[parseInt(Math.random()*colors.length,10)]
value = values[parseInt(Math.random()*values.length,10)]

How can I make sure that there is no repetition if I pick 5 cards?

Harsh Baid
  • 7,199
  • 5
  • 48
  • 92
Floor Drees
  • 118
  • 5

3 Answers3

10

Prepare an array of all 48 cards (are you missing Aces?)

Every time you pick a card, remove it from the array.

The next draw will be from the reduced array, so there can be no duplicates.

Alternative:

Start with the same array, then shuffle it. Take the first five cards.

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • I would go for the second approach (Shuffle array) - a Fisher-Yates-Shuffle does the trick http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle – Gregor Sep 19 '13 at 11:59
3

You could also create a markerlist, where you put in the already used card!

var myGivenCards = {}

repeat that for every card:

color = colors[parseInt(Math.random()*colors.length,10)]
value = values[parseInt(Math.random()*values.length,10)]
if (typeof(myGivenCards[color+values])==='undefined') {
  //not used
  myGivenCards[color+values] = true;
}
Joe
  • 461
  • 4
  • 6
  • Why are you using `parseInt`? The normal way of casting a floating point value to an integer is using `Math.floor` (or `ceil`, or `round`), not convert it to a string and parse it. Please don't do things like that, it's a bad practice. – AJMansfield Sep 19 '13 at 15:18
2

As others said, use a Fisher-Yates-Shuffle, then pick the first five:

 var colors = ["hearts", "spades", "diamonds", "clubs"];
 var values = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

 // from http://jsfromhell.com/array/shuffle by Jonas Raoni Soares Silva
 function shuffle(o) { //v1.0
     for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
     return o;
 };

 var cards = [];
 for (var j = 0; j < colors.length; j++) {
     for (var i = 0; i < values.length; i++) {
         cards.push(colors[j] + values[i]);
     }
 }
 shuffle(cards);
 console.log(cards.slice(0, 5));
Thorben Croisé
  • 12,407
  • 8
  • 39
  • 50