Is it possible to create several variables and using the rand () function from these variables to randomly select one?
- You can create an array of, say, five elements and randomly select an index - from one to five. It's all right? - Jenssen
- just want to create a game (with registration). And when a random number fell out (if from 1 to 7, it fell out 7) and in parallel creating a variable of type string seven with the value of the text (as a seven), it displayed the text of the variable seven - Allyans
|
2 answers
int a, b, c; int& x = (rand() > 3000) ? a : (rand() < 2000) ? b : c; Will arrange?
This is if you need a variable - with the ability to record, etc. If its value is even simpler,
int x = (rand() > 3000) ? a : (rand() < 2000) ? b : c; Naturally, rand() must be used wisely; here I just cited an example ...
This all makes sense when you already have variables from which to make a choice. If you create them yourself ... of course, you can work with an array, a vector, etc., but I have a suspicion that it is a question of what kind of hand to keep the microscope when nailing. Do you really need exactly the variables and the choice of one of them?
- Yes, I still think that I need. I'm confused a little. - Allyans
- Well, if I create, let's say 3 variables of type string with values that I need to display. and I need to randomly select one of the three. in this case how can I be? - Allyans
- Values can be generated, can - just literals. In the latter case, you don't even need a variable :) -
std::cout << ((rand()%3) ? (rand()%2) ? "First" : "Second" : "Third") << std::endl;- Harry - 1. Call rand twice incorrectly. 2. Probabilities are strange. - Qwertiy ♦
- @Qwertiy Yes, this is like an example, in the comments write the code seriously and in detail, with variables ...: ( - Harry
|
You can do it through an array:
std::vector<int> v(5, 0); // устанавливаем значения в массиве int value = v.at(rand() % 5); This method allows you to arrange everything briefly, if you expect a large number of variables.
- It is better to make an array of pointers to variables if they are to be changed. - Constructor
rand()%5may not return indices with equal probability - jfs- @Constructor array of pointers to variables? but why? vector / array will cover 99% of the needs in this case. - KoVadim
- @KoVadim For the remaining 1%, obviously. - Constructor
- Give such an example please. - KoVadim
|