How to get different result from function

I call the function twice and got the same result. How can I make them give me two different cards? I tried creating a different function with the same code and different names but still got the same cards.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int random_number;
int random_suit;

void generate_random_card();

string card_number[] = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
string card_suit[] = {" Spade", " Heart", " Club", " Diamond"};

int main (){
    generate_random_card();
    generate_random_card();
    return 0;
}

void generate_random_card()
{
    srand(time(NULL));
    random_number = rand()%13;
    random_suit = rand()%4;

    cout << card_number[random_number];
    cout << card_suit[random_suit];
    cout << endl;
}
Move line 22 to just after line 14.

srand() "seeds" the random number generator. If you give it the same seed, then rand() it will generate the same sequence of random numbers each time it's called. You're passing the current time as the seed, so unless the system clock rolls over from one second to the next between those two calls, it will get the same seed, and the same random number sequence.
Using the <random> library, and passing references to main() created variables:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <random>

// int random_rank;
// int random_suit;

void generate_random_card(int&, int&);

// std::string card_number[] = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
// std::string card_suit[] = { " Spade", " Heart", " Club", " Diamond" };

int main()
{
   int random_rank { };
   int random_suit { };

   // lambdas to display the card in text representation:
   auto rank = [] (int r) { return "AKQJT98765432"[r % 13]; };
   auto suit = [] (int s) { return "SHDC"[s % 4]; };

   std::cout << rank(random_rank) << suit(random_suit) << "\n\n";

   generate_random_card(random_rank, random_suit);
   std::cout << rank(random_rank) << suit(random_suit) << '\n';

   generate_random_card(random_rank, random_suit);
   std::cout << rank(random_rank) << suit(random_suit) << '\n';
}

void generate_random_card(int& c_rank, int& c_suit)
{
   static std::default_random_engine rng(std::random_device{}());

   // random_number = rand() % 13;
   static std::uniform_int_distribution<int> rank(0, 12);
   c_rank = rank(rng);

   // random_suit = rand() % 4;
   static std::uniform_int_distribution<> suit(0, 3);
   c_suit = suit(rng);
}

AS

9D
4H
Topic archived. No new replies allowed.