0

I am fairly new to javascript and had some trouble making a program. I want the program to ask the user how many cards they want to draw from a deck, but I need help getting my program to type how many cards of each suite were picked in the end.

var NUM =  readInt("How many cards will you draw from the deck?");
var RANDOM = Randomizer.nextBoolean();
var DIAMONDS = "Diamonds";
var HEARTS = "Hearts";
var SPADES = "Spades";
var CLUBS = "Clubs";

function start(){
    var take = takeCard();
    printArray(take);
    countCards(take);
}

// This function will pick a random card from the deck.
//Needs Work
function takeCard(){
    var pick = [];
    for(var i = 0; i < NUM; i++){
    if(Randomizer.nextBoolean()){
        pick.push(DIAMONDS);
        }else{
            pick.push(HEARTS);
            pick.push(SPADES);
            pick.push(CLUBS);
        }
    }
    return pick;
}

// Displays the array
function printArray(arr){
    for(var i = 0; i < arr.length; i++){
        println("Flip Number " + (i+1) + ": " + arr[i]);
    }
}

//Counts the number of Cards in each suite
//Needs Work
function countCards(take){
    var countOne = 0;
    var countTwo = 0;
    var countThree = 0;
    var countFour = 0;
    for(var i = 0; i < take.length; i++){
        if(take[i] == "Heads"){
        countOne++;
    } else {
        countTwo++;
    }
    }
    println("Number of Diamonds: " + countOne);
    println("Number of Hearts: " + countTwo);
    println("Number of Spades: " + countThree);
    println("Number of Clubs: " + countFour);
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 1
    `readInt` and `Randomizer` are missing from your example. It's also hard to reconcile your description of the problem with your attempted solution. eg, why are you adding 3 cards if the random boolean is false? – Jamiec Mar 09 '21 at 14:38
  • You are checking to see if a given card is "heads", and I believe you meant to check for "hearts": `take[i] == "Heads"` However, you should use the constants you've already defined, so that check might look like: `take[i] == HEARTS` – zeterain Mar 09 '21 at 14:41

1 Answers1

2

This looks like homework, so rather than give you an entire working solution I'll explain how to break this down and leave you to write the code.

You should start by generating an entire deck of cards. There are 4 suits and 13 cards per suit. So this is as easy as 2 loops (one for suit one for card). Push each card into an array so you end up with an array of 52 elements

Then shuffle the pack. The easiest way of doing that is with something called a "Fisher-Yates shuffle". You can learn how to do it in javascript here: How to randomize (shuffle) a JavaScript array?

Then, you ask the user how many cards and simply take that many from the front of the array using Array.splice.

Finally, you loop over that set you have extracted counting the different suits.

Jamiec
  • 133,658
  • 13
  • 134
  • 193