Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mix values in a JavaScript array without repetition?

Tags:

javascript

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?

like image 290
Floor Drees Avatar asked Sep 19 '13 11:09

Floor Drees


1 Answers

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.

like image 170
Thilo Avatar answered Oct 20 '22 22:10

Thilo