Another feature of SMath
is to rearrange arrays using the SMath.shuffle()
function. We can use this to shuffle a deck of cards, for example.
Follow these steps to create a new project workspace and install the smath dependency to run this example.
# Create and open project folder
mkdir Deck_Shuffler_demo
cd Deck_Shuffler_demo
# Initialize project and install dependencies
npm init -y
npm i smath@1.12.0
# Create and open source file
touch "Deck Shuffler.mjs"
open "Deck Shuffler.mjs"
Copy and paste this source code into Deck Shuffler.mjs
.
import { SMath } from 'smath';
// Define the suits and values of cards in the deck
const suits = ['clubs', 'diamonds', 'spades', 'hearts'],
values = ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king'],
cards = [];
// Generate the deck of cards
suits.forEach(suit => values.forEach(value => cards.push(value + ' of ' + suit)));
// Shuffle the deck
const shuffled = SMath.shuffle(cards);
// Draw the top 5 cards
for (let i = 0; i < 5; i++) {
console.log(shuffled[i]);
}
In Deck_Shuffler_demo/
, execute Deck Shuffler.mjs
with NodeJS to generate an output.
node "Deck Shuffler.mjs"
You should expect to see an output similar to the one below.
four of diamonds
six of spades
two of hearts
queen of hearts
queen of clubs