Shuffle a deck of cards
Sat Jun 19 2021 07:31:06 GMT+0000 (UTC)
Saved by @hisam #javascript #vanilla #sort #randomize #array
In the above program, the suits and values variables contain the elements of a card. The nested for loop is used to create a deck of cards. We need to create a deck of cards containing each suits with all the values. So the first for loop iterates over all the suits and the second for loop iterates over the values. Then, the elements are created and added to the deck array. The array elements are stored as an object as: [{Value: "Ace", Suit: "Spades"},{Value: "2", Suit: "Spades"}.....] The second for loop is used to shuffle the deck of cards. Math.random() generates a random number. Math.floor() returns the number by decreasing the value to the nearest integer value. A random number is generated between 0 and 51 and two card positions are swapped. The third for loop is used to display the first five cards in the new deck.
Comments