Example: Shuffle Deck of Cards
// program to shuffle the deck of cards
// declare card elements
const suits = ["Spades", "Diamonds", "Club", "Heart"];
const values = [
"Ace",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"Jack",
"Queen",
"King",
];
// empty array to contain cards
let deck = [];
// create a deck of cards
for (let i = 0; i < suits.length; i++) {
for (let x = 0; x < values.length; x++) {
let card = { Value: values[x], Suit: suits[i] };
deck.push(card);
}
}
// shuffle the cards
for (let i = deck.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * i);
let temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
console.log('The first five cards are:');
// display 5 results
for (let i = 0; i < 5; i++) {
console.log(`${deck[i].Value} of ${deck[i].Suit}`)
}
//output
The first five cards are:
4 of Club
5 of Diamonds
Jack of Diamonds
2 of Club
4 of Spades
Comments