commit 86f340e6bcb4e749ca0e7e9b49243f30bbdc73f7
parent 1426cdc037f58ec99b2d569ac97351195303044e
Author: = <=>
Date: Wed, 8 Oct 2025 20:57:35 +0300
c++ solution added
Diffstat:
| M | .gitignore | | | 2 | ++ |
| A | solution.cpp | | | 125 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
2 files changed, 127 insertions(+), 0 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -0,0 +1 @@
+.vscode
+\ No newline at end of file
diff --git a/solution.cpp b/solution.cpp
@@ -0,0 +1,124 @@
+#include <iostream>
+#include <vector>
+#include <algorithm>
+#include <random>
+#include <string>
+#include <ctime>
+
+class Guesser {
+private:
+ std::vector<std::string> possible_numbers;
+
+ bool isValidNumber(const std::string& num) {
+ for (int i = 0; i < 4; i++) {
+ for (int j = i + 1; j < 4; j++) {
+ if (num[i] == num[j]) return false;
+ }
+ }
+ return true;
+ }
+
+ void calculateBullsCows(const std::string& num1, const std::string& num2, int& bulls, int& cows) {
+ bulls = 0;
+ cows = 0;
+
+ for (int i = 0; i < 4; i++) {
+ if (num1[i] == num2[i]) {
+ bulls++;
+ }
+ else if (num2.find(num1[i]) != std::string::npos) {
+ cows++;
+ }
+ }
+ }
+
+public:
+ Guesser() {
+
+ for (int i = 0; i <= 9999; i++) {
+ std::string num = std::to_string(i);
+
+ while (num.length() < 4) {
+ num = "0" + num;
+ }
+ if (isValidNumber(num)) {
+ possible_numbers.push_back(num);
+ }
+ }
+
+ std::shuffle(possible_numbers.begin(), possible_numbers.end(),
+ std::default_random_engine(time(0)));
+ }
+
+ std::string makeGuess(int attempt) {
+ if (possible_numbers.empty()) return "";
+
+ if (attempt == 1) {
+ return "0123";
+ }
+
+ if (attempt == 2) {
+ return "6789";
+ }
+
+ return possible_numbers[0];
+ }
+
+ void processResult(const std::string& guess, int bulls, int cows) {
+ std::vector<std::string> new_list;
+
+ for (const auto& num : possible_numbers) {
+ int b, c;
+ calculateBullsCows(num, guess, b, c);
+ if (b == bulls && c == cows) {
+ new_list.push_back(num);
+ }
+ }
+
+ possible_numbers = new_list;
+
+ if (!possible_numbers.empty()) {
+ std::shuffle(possible_numbers.begin(), possible_numbers.end(),
+ std::default_random_engine(time(0)));
+ }
+ }
+
+ bool hasGuesses() const {
+ return !possible_numbers.empty();
+ }
+};
+
+int main() {
+
+ Guesser g;
+ int attempt = 0;
+
+ while (g.hasGuesses()) {
+ attempt++;
+ std::string guess = g.makeGuess(attempt);
+
+ std::cout << "\nTry " << attempt << ": " << guess << std::endl;
+
+ std::cout << "Bulls: ";
+ int bulls;
+ std::cin >> bulls;
+
+ if (bulls == 4) {
+ std::cout << "Cows: 0" << std::endl << std::endl;
+ std::cout << "Steps amount: " << attempt << std::endl;
+ break;
+ }
+
+ std::cout << "Cows: ";
+ int cows;
+ std::cin >> cows;
+
+ g.processResult(guess, bulls, cows);
+
+ if (!g.hasGuesses()) {
+ std::cout << std::endl << "Unreal number. And Afanasev is gad." << std::endl;
+ }
+ }
+
+ return 0;
+}
+\ No newline at end of file