Search code examples
javascriptrandomlodashshuffleplaying-cards

Javascript- Lodash shuffle vs. Math.Random()


I'm in the process of coding a simple BlackJack game in Javascript. So far, I have an array like this:

var deckArray = [ "card1", "card2",...,"card52" ]

I have a "deal" function set up like this:

var deal = function(){
   var card = Math.floor(Math.random() * deckArray.length);
   return deckArray.splice(card,1)[0];
};

Since I'm already using Math.random to randomly choose from the deckArray, would it be redundant for me to incorporate a "shuffle" function with Lodash like this?

var shuffle = function(){
  deckArray = _.shuffle(deckNames);
};

Solution

  • I think it would. With real cards we shuffle the deck and then pick some cards from the top of the top of the deck. This is what you'll probably be doing with the shuffle function, thereby modelling the real world use.

    With Math.Random(), you're randomly picking a card from an un-shuffled deck. The key here is randomness (which is not really random btw). So, although this isn't modelled after the real world use, the end result is the same.

    I would suggest Math.Random() because it will, although not significantly, be faster than using _.shuffle's (Fisher–Yates) algorithm.