solution.cpp (2552B)
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <random> 5 #include <string> 6 #include <ctime> 7 8 class Guesser { 9 private: 10 std::vector<std::string> possible_numbers; 11 12 bool isValidNumber(const std::string& num) { 13 for (int i = 0; i < 4; i++) { 14 for (int j = i + 1; j < 4; j++) { 15 if (num[i] == num[j]) return false; 16 } 17 } 18 return true; 19 } 20 21 void calculateBullsCows(const std::string& num1, const std::string& num2, int& bulls, int& cows) { 22 bulls = 0; 23 cows = 0; 24 25 for (int i = 0; i < 4; i++) { 26 if (num1[i] == num2[i]) { 27 bulls++; 28 } 29 else if (num2.find(num1[i]) != std::string::npos) { 30 cows++; 31 } 32 } 33 } 34 35 public: 36 Guesser() { 37 38 for (int i = 0; i <= 9999; i++) { 39 std::string num = std::to_string(i); 40 41 while (num.length() < 4) { 42 num = "0" + num; 43 } 44 if (isValidNumber(num)) { 45 possible_numbers.push_back(num); 46 } 47 } 48 49 std::shuffle(possible_numbers.begin(), possible_numbers.end(), 50 std::default_random_engine(time(0))); 51 } 52 53 std::string makeGuess(int attempt) { 54 if (possible_numbers.empty()) return ""; 55 56 if (attempt == 1) { 57 return "0123"; 58 } 59 60 if (attempt == 2) { 61 return "6789"; 62 } 63 64 return possible_numbers[0]; 65 } 66 67 void processResult(const std::string& guess, int bulls, int cows) { 68 std::vector<std::string> new_list; 69 70 for (const auto& num : possible_numbers) { 71 int b, c; 72 calculateBullsCows(num, guess, b, c); 73 if (b == bulls && c == cows) { 74 new_list.push_back(num); 75 } 76 } 77 78 possible_numbers = new_list; 79 80 if (!possible_numbers.empty()) { 81 std::shuffle(possible_numbers.begin(), possible_numbers.end(), 82 std::default_random_engine(time(0))); 83 } 84 } 85 86 bool hasGuesses() const { 87 return !possible_numbers.empty(); 88 } 89 }; 90 91 int main() { 92 93 Guesser g; 94 int attempt = 0; 95 96 while (g.hasGuesses()) { 97 attempt++; 98 std::string guess = g.makeGuess(attempt); 99 100 #ifdef TESTER 101 std::cout << guess << std::endl; 102 #else 103 std::cout << "\nTry " << attempt << ": " << guess << std::endl; 104 #endif 105 106 #ifndef TESTER 107 std::cout << "Bulls: "; 108 #endif 109 int bulls; 110 std::cin >> bulls; 111 112 if (bulls == 4) { 113 #ifdef TESTER 114 std::cout << "Cows: 0" << std::endl << std::endl; 115 std::cout << "Steps amount: " << attempt << std::endl; 116 #else 117 std::cout << "0" << std::endl << std::endl; 118 break; 119 } 120 121 #ifndef TESTER 122 std::cout << "Cows: "; 123 #endif 124 int cows; 125 std::cin >> cows; 126 127 g.processResult(guess, bulls, cows); 128 129 if (!g.hasGuesses()) { 130 std::cout << std::endl << "Unreal number. And Afanasev is gad." << std::endl; 131 } 132 } 133 134 return 0; 135 }