Card shuffle until it gets spade card


#1

can someone help me understand this code:

var cards = ['Diamond', 'Spade', 'Heart', 'Club'];
var currentCard = 'Heart';

while (currentCard !== 'Spade') {
console.log(currentCard);

var randomNumber = Math.floor(Math.random() * 4);

currentCard = cards[randomNumber];
}
console.log('Found a Spade');


#2

we have an array with the different card types (diamonds, spade and so on)

Then we select a starting car (heart)

then we loop until we find a spade. In the loop, each iteration of the loop we generate a random number, this number is used as index to pick card from array, causing a random card. once spade is picked, the loop condition becomes false, the loop ends, you inform the user they found a spade


#3

so it means that this code "var randomNumber = Math.floor(Math.random() * 4);
currentCard = cards[randomNumber];"
is for indexing the items in the array only?


#4

no, the random number generated is used as index to retrieve card type from array, given the number generated is random, so is the card picked


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.