Reputation: 39
In C++ is it possible to use rand to generate a number between 1-52, but stating that it cant be 23? Like for instance creating a blackjack game, you would need to make sure a player cant get the same card after randomly generating the first.
Upvotes: 2
Views: 2269
Reputation: 76285
Sure.
int i = 23;
while (i == 23)
i = rand() % 52 + 1;
It's quite common to discard unacceptable values when generating random numbers with a required distribution.
For a blackjack game, though, you need to deal more than one card. It's better to have a full deck and shuffle it (std::random_shuffle
), then take cards from one end of whatever container holds the deck.
Upvotes: 13
Reputation: 17521
Another cool way to do this is with an array.
Create a vector:
std::vector<int> possibilities;
Insert possible values to it:
possibilities.push_back(0);
possibilities.push_back(1);
possibilities.push_back(10);
And then pick a random one from it:
int random = possibilites[ rand() % possibilites.size() ];
Upvotes: 0
Reputation: 22529
Here's a program that makes a deck from 1 to 52 (inclusive) and prints the deck. This features STL (and a slightly dated C++ accent)
#include <algorithm> // std::random_shuffle
#include <ctime> // std::time
#include <cstdlib> // std::rand, std::srand
#include <iostream> // std::cout
#include <vector> // std::vector
int main() {
std::vector<int> deck;
// Create deck; deck creation logic goes inside loop
for (int i = 1; i <= 52; ++i) {
deck.push_back(i);
}
// initialize random number generator and shuffle deck
std::srand(std::time(0));
std::random_shuffle(deck.begin(), deck.end());
// print entire deck
while (!deck.empty()) {
int card = deck.back(); // draw card
std::cout << "Drew " << card << '\n';
deck.pop_back(); // remove card from deck
}
}
Upvotes: 1
Reputation: 254461
int value = rand(1,51);
if (value >= 23) ++value;
where rand(a,b)
gives a number in the range [a,b]
, and could be implemented as std::rand() % (b-a+1) + a
, with the caveat that that wouldn't quite be a uniform distribution.
Upvotes: 4
Reputation: 9577
int n=(rand() % 52)+ 1;
while(n==23)
n= n=(rand() % 52) + 1;
http://www.cplusplus.com/reference/cstdlib/rand/
Upvotes: 0