8

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);
};
3
  • 1
    Either is fine. Btw, as you're learning - it would be a good habit to stop using global variables and passing a deck as an argument of the deal function.
    – zerkms
    Commented Oct 10, 2016 at 23:33
  • And representing cards with strings is bad too. Strings are for humans--computers use numbers. Commented Oct 11, 2016 at 20:42
  • Lodash's Fisher-Yates implementation uses Math.random: github.com/lodash/lodash/blob/master/shuffle.js
    – opyate
    Commented Oct 19, 2020 at 7:56

1 Answer 1

8

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.

1
  • 1
    This my sound like a bit of nitpick, because it is; however, I would question why in this case speed is of any significance? It seems to me, whichever implementation is used, the speed difference is absolutely insignificant given the usage pattern in this case. Though, I do agree with the rest of your answer in terms of how a real deck of cards is shuffled. Commented Sep 29, 2021 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.