Javascript- Lodash shuffle vs. Math.Random()
Asked Answered
R

1

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);
};
Rowe answered 10/10, 2016 at 23:28 Comment(3)
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.Durman
And representing cards with strings is bad too. Strings are for humans--computers use numbers.Melodee
Lodash's Fisher-Yates implementation uses Math.random: github.com/lodash/lodash/blob/master/shuffle.jsBuddhology
B
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.

Bim answered 10/10, 2016 at 23:36 Comment(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.Revitalize

© 2022 - 2024 — McMap. All rights reserved.