admin管理员组

文章数量:1401623

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?

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?

Share Improve this question edited Sep 19, 2013 at 12:06 Harsh Baid 7,2496 gold badges50 silver badges92 bronze badges asked Sep 19, 2013 at 11:54 Floor DreesFloor Drees 1185 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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.

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;
}

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./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));

本文标签: How to mix values in a JavaScript array without repetitionStack Overflow