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:

  1. 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.

  2. 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; } 
  • And why this wisdom with the seed ? Just specify the current time in milliseconds and each time you start there will be random numbers - gil9red
  • Strand is not thread safe. - typemoon
  • @ gil9red I am not familiar with this feature unfortunately. - its_space
  • one
    Use <random> C ++ - typemoon
  • 3
    And you did not consider the option, what would happen if all four digits become the same?)) Make an intermediate collection with all possible options (1-9), then take a random position four times the length of the collection and take this number from the position with the deletion. - Alex Krass

1 answer 1

For example, here is a complete solution of the problem. The solution does not check ranges, user input, the code is made more for ease of parsing, and so is the memory (!) I have already forgotten C ++.

 #include <iostream> #include <cstdlib> #include <vector> #include <ctime> using namespace std; /*функция для генерации неповторяющихся цифр*/ vector<int> initialGameNumbers(); /*функция ввода пользователем цифр*/ vector<int> getUserNumbers(); /*функция проверки количества "быков" и "коров"*/ vector<int> checkBullsAndCows(vector<int> v1, vector<int> v2); /*печать значений вектора на экран*/ void printVectorInt(vector<int> v); int main(int argc, char **argv) { vector<int> bullsAndCows; vector<int> sequence_four; vector<int> sequence_user; sequence_four = initialGameNumbers(); while(true) { sequence_user = getUserNumbers(); bullsAndCows = checkBullsAndCows(sequence_four, sequence_user); if(bullsAndCows[0] == 4) break; cout << "быки: " << bullsAndCows[0] << " коровы: " << bullsAndCows[1] << endl << endl; } cout << "Загаданная последовательность:" << endl; printVectorInt(sequence_four); return 0; } vector<int> initialGameNumbers() { srand(time(0)); vector<int> seq; //заводим последовательность требуемых чисел 0..9 for(int i = 0; i < 10; i++) seq.push_back(i); vector<int> ret; for(int i = 0; i < 4; i++) { int pos = rand() % seq.size(); //получаем рандомную позицию элемента ret.push_back(seq[pos]); //вставляем элемент из позицию pos в конечный массив seq.erase(seq.begin() + pos); //удаляем элемент из последовательности, что бы он снова не появился /* // Визуализация работы, раскомментируйте если надо cout << "шаг " << i << endl; printVectorInt(seq); cout << endl; printVectorInt(ret); cout << endl << endl; */ } return ret; } vector<int> getUserNumbers() { vector<int> ret; cout << "Введите четыре цифры используя <enter>:" << endl; int n; for(int i = 0; i < 4; i++) { cin >> n; ret.push_back(n); } return ret; } vector<int> checkBullsAndCows(vector<int> v1, vector<int> v2) { vector<int> ret(2); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { if(v1[i] == v2[j]) { if(i == j) ret[0] += 1; else ret[1] += 1; break; } } } return ret; } void printVectorInt(vector<int> v) { vector <int>::iterator cur; for(cur = v.begin(); cur < v.end(); cur++) cout << *cur << " "; }