There is such a problem in Björn Straustrup, "Bulls and cows."
Its essence is as follows. the computer generates four random numbers and writes them into a container. The user must guess what number the computer made.
For example, the computer made a guess of 1234 , and the user answered 1356 . The first element of the user's response coincides with the computer and the values 1 are in the same positions, which means the answer is “Bull.” If it coincides with the meaning of 3 , but the positions are different, then this is the “Cow”.
Actually, I have two questions:
What if the computer generates such a number where the values are repeated, for example 1232 ?
Then the answers will not be correct, as I compare all the values. In principle, I can scan the vector in advance, find these identical values and change them, but I have doubts whether this is acceptable.
How to improve my code?
// Функция start_game() генирирует случайные числа , записывает их в вектор. void start_game(int seed) { const int v1_size = 4; if(seed < 0) seed = -seed; // if -seed = - seed == +seed. seed %= 10; // остаток от деления. if (seed == 0) return; srand(seed); // генирируем случаные числа. for (int i = 0; i < v1_size; ++i) v1.push_back(rand() % 9 + 1); } int main() { try { int seed, bulls = 0, cows = 0; int k = 0; cin >> seed; start_game(seed); for (auto i : v1) cout << i << ends; cout << endl; for (auto i = 0;i < v1.size() ;++i){ cout << "enter: "; int users; while (!(cin >> users)) { cin.clear(); while (cin.get() != '\n'); cout << "enter: "; } v2.push_back(users); for (; k < v2.size();k+=1) { int a = v2[k]; int k_v2 = k; for (int j = 0; j < v1.size(); ++j) { int b = v1[j]; int j_v1 = j; if (a == b) { if (k_v2 == j_v1) { ++bulls; cout << setw(15) << "bulls: " << bulls << endl; break; } else ++cows; cout << setw(15) << "cows: " << cows << endl; } } } } } return 0; }
seed
? Just specify the current time in milliseconds and each time you start there will be random numbers - gil9red