Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
};
like image 544
KnowledgeMC Avatar asked Oct 10 '16 23:10

KnowledgeMC


People also ask

What is Lodash shuffle?

Lodash is a JavaScript library that works on the top of underscore. js. Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. shuffle() method creates an array of shuffled values from the given collection using a version of the Fisher-Yates shuffle algorithm.

Is there a shuffle function in JavaScript?

Write the function shuffle(array) that shuffles (randomly reorders) elements of the array. Multiple runs of shuffle may lead to different orders of elements. For instance: let arr = [1, 2, 3]; shuffle(arr); // arr = [3, 2, 1] shuffle(arr); // arr = [2, 1, 3] shuffle(arr); // arr = [3, 1, 2] // ...


1 Answers

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.

like image 128
reggaemahn Avatar answered Oct 12 '22 12:10

reggaemahn