This code snippet selects a random element from an array.
var shape = shapes[Math.floor(Math.random() * shapes.length)];
To make this process more user-friendly, you can convert it into a function like this:
function getRandomElement(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
Now, it becomes simple to pick multiple random elements from the array:
var shape1 = getRandomElement(shapes);
var shape2 = getRandomElement(shapes);
However, there's a chance that both shape1
and shape2
could be the same. To avoid this, we can modify the function to ensure uniqueness:
function getUniqueRandomElements(arr, count) {
if (!count) count = 1;
var copy = arr.slice(0);
var result = [];
for (var i=0; i<count; i++) {
var index = Math.floor(Math.random() * copy.length);
result = result.concat(copy.splice(index, 1));
}
return result;
}
With this version of the function, duplicates are eliminated:
var letters = ["a", "b", "c", "d", "e"];
getUniqueRandomElements(letters, 3); // ["e", "c", "b"]
getUniqueRandomElements(letters, 3); // ["e", "a", "d"]
getUniqueRandomElements(letters, 3); // ["c", "a", "b"]
A useful enhancement can be made to this code by incorporating card shuffling functionality. Consider these two approaches:
- Select 2 cards randomly from a sorted/unsorted deck
- Shuffle the deck and pick 2 cards from the top
The existing getUniqueRandomElements
function aligns with method #1. By adjusting it to match method #2, we can obtain a shuffle function as well!
Here's how the modified function would look:
function getRandomNumber(x) {
return Math.floor(Math.random() * x);
}
function shuffleCards(deck) {
var copy = deck.slice(0);
return deck.reduce(function(shuffledDeck, card) {
var position = getRandomNumber(copy.length);
return shuffledDeck.concat(copy.splice(position, 1));
}, []);
}
function getUniqueRandomElements(arr, n) {
return shuffleCards(arr).slice(0, n || 1);
}
By taking this approach, we achieve our initial goal while gaining reusable functions getRandomNumber
and shuffleCards
. This demonstrates the power of writing getUniqueRandomElements
as a higher-order procedure! 🌟