I know randomness in programming can be a deep topic, and searching the topic seems to result in Fisher-Yates being the best method, but I'm curious what people would say about this method.
Basically, since I have the cards as objects, I just add a property of a random number then sort the entire array based on those random numbers.
const suits = [
{
digit: 'H',
word: 'hearts'
},
{
digit: 'C',
word: 'clubs'
},
{
digit: 'D',
word: 'diamonds'
},
{
digit: 'S',
word: 'spades'
}
]
const cardsWithoutSuits = [
{
numeric: 1,
word: 'ace',
digit: 'A'
},
{
numeric: 2,
word: 'two',
},
{
numeric: 3,
word: 'three',
},
{
numeric: 4,
word: 'four',
},
{
numeric: 5,
word: 'five',
},
{
numeric: 6,
word: 'six',
},
{
numeric: 7,
word: 'seven',
},
{
numeric: 8,
word: 'eight',
},
{
numeric: 9,
word: 'nine',
},
{
numeric: 10,
word: 'ten',
},
{
numeric: 11,
word: 'jack',
digit: 'J'
},
{
numeric: 12,
word: 'queen',
digit: 'Q'
},
{
numeric: 13,
word: 'king',
digit: 'K'
}
]
function createDeck(decks = 1){
let deck = [];
for (let i = 0; i < decks; i++) {
suits.forEach( x => {
cardsWithoutSuits.forEach( y => {
deck.push({
numeric: y.numeric,
word: y.word,
suit: x.word,
phrase: `${y.word} of ${x.word}`,
abbr: `${y.hasOwnProperty('digit') ? y.digit : y.numeric}${x.digit}`
})
})
})
}
return deck;
}
function shuffle(array){
array.forEach( x =>{
x.ran = Math.random();
})
array.sort( (a, b) =>{
return a.ran - b.ran;
})
return array;
}
let deck = shuffle(createDeck(2));
console.log(deck);
O(n*lg(n))
while Fisher-Yates and friends are linear in n. And a big problem with pseudo-random number generators as shufflers is that they have far fewer possible permutations than a deck of cards. 52 factorial is about 8e67; compare to Chrome's Math.random() with 128 bits of internal state - about 3e38 possible states. For a given real-world deck ordering, the odds are only about 1 in a nonillion that your algorithm can produce it in a better-than-average JavaScript engine. \$\endgroup\$ – Oh My Goodness Jan 26 '19 at 8:19