Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ This code creates a deck for a game in another file. My issue is everytime I

ID: 3754893 • Letter: C

Question

C++

This code creates a deck for a game in another file. My issue is everytime I compile the code and get an executable , the results are the same in terms of the deck being shuffled. How can I generate different results everytime ?

#include <iostream>
#include "card.cpp"
#include <stdlib.h>
#include <time.h>
#include <stdio.h>

using namespace std;
//randomInteger randomizer;


class Deck {
public:
Deck();

void shuffle();
bool isEmpty();
Card draw();

protected:
Card cards[52];
int topCard;

};

class randomInteger {
public:
unsigned int operator () (unsigned int);
};

randomInteger randomizer;


unsigned int randomInteger::operator () (unsigned int max)
{
unsigned int rval = rand();
return rval % max;

}

Deck::Deck()
{
topCard = 0;
for(int i = 1; i <= 13; i++) {
Card c1(diamond, i), c2(spade, i), c3(heart, i), c4(club, i);
cards[topCard++] = c1;
cards[topCard++] = c2;
cards[topCard++] = c3;
cards[topCard++] = c4;
}

}

bool Deck::isEmpty()
{
return topCard <= 0;
}

void Deck::shuffle()
{
random_shuffle (cards, cards+52, randomizer);
}

Card Deck::draw()
{
if(!isEmpty())
return cards[topCard--];
else {
Card spadeAce(spade, 1);
return spadeAce;
}
}

Explanation / Answer

#include <iostream>

#include "card.cpp"

#include <stdlib.h>

#include <time.h>

#include <stdio.h>

using namespace std;

randomInteger randomizer;

class Deck {

public:

Deck();

void shuffle();

bool isEmpty();

Card draw();

protected:

Card cards[52];

int topCard;

};

class randomInteger {

public:

unsigned int operator () (unsigned int);

};

randomInteger randomizer;

unsigned int randomInteger::operator () (unsigned int max)

{

srand(time(NULL)); //Try this , It should work NOW

unsigned int rval = rand();

return rval % max;

}

Deck::Deck()

{

topCard = 0;

for(int i = 1; i <= 13; i++) {

Card c1(diamond, i), c2(spade, i), c3(heart, i), c4(club, i);

cards[topCard++] = c1;

cards[topCard++] = c2;

cards[topCard++] = c3;

cards[topCard++] = c4;

}

}

bool Deck::isEmpty()

{

return topCard <= 0;

}

void Deck::shuffle()

{

random_shuffle (cards, cards+52, randomizer);

}

Card Deck::draw()

{

if(!isEmpty())

return cards[topCard--];

else {

Card spadeAce(spade, 1);

return spadeAce;

}

}




Try the One I added in BOLD. Thanks, PLEASE UPVOTE if helpful

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote