diff --git a/cpp/24game.cpp b/cpp/24game.cpp index 0da81d7..a288125 100644 --- a/cpp/24game.cpp +++ b/cpp/24game.cpp @@ -1,17 +1,176 @@ +// Reference code: https://www.jb51.net/article/182079.htm #include #include #include +#include -//生成在[begin,end]范围内的随机数 -double randnum(int begin = 0, int end = 1){ - srand(time(NULL)); - return (rand()%(end-begin+1))+begin; +typedef std::string string; + +// Generate a number in [begin,end] +static double randnum(int begin = 0, int end = 1) +{ + return rand() % (end - begin + 1) + begin; } -//24点主类 -class Game24{}; +// The Game Class +class Game24 +{ +public: + Game24() {} -int main(int argc, char ** argv){ - printf("%f",randnum(1,13)); + void startgame() + { + bool winned = false; + string user_result; + getnumbers(); + std::cin >> user_result; + + // Format result number + if(user_result[user_result.length()] != ')' || user_result[0] != '('){ + user_result = '(' + user_result + ')'; + } + + // Check user input and the results + for (std::vector::iterator it = result_strings.begin(); it != result_strings.end(); it++) + { + if (*it == user_result) + { + std::cout << "Winned!" << std::endl; + winned = true; + break; + } + else + { + continue; + } + } + + // If lost, output information + if(!winned){ + std::cout<<"Lost"< result_strings; + + void F(int n) + { + // Calculate for three times + if (n == 1) + { + if (number[0] == 24) + { + //std::cout << result[0] << std::endl; + result_strings.push_back(result[0]); + count++; + } + } + + for (int i = 0; i < n; i++) + { + for (int j = i + 1; j < n; j++) + { + double a, b; + string x, y; + + // Save number + a = number[i]; + b = number[j]; + number[j] = number[n - 1]; + + // Save Result String + x = result[i]; + y = result[j]; + result[j] = result[n - 1]; + + // Add + number[i] = a + b; + result[i] = '(' + x + '+' + y + ')'; + F(n - 1); + + // Minus + number[i] = a - b; + result[i] = '(' + x + '-' + y + ')'; + F(n - 1); + number[i] = b - a; + result[i] = '(' + y + '-' + x + ')'; + F(n - 1); + + // multiply + number[i] = a * b; + result[i] = '(' + x + '*' + y + ')'; + F(n - 1); + + // divide + if (b != 0) + { + number[i] = a / b; + result[i] = '(' + x + '/' + y + ')'; + F(n - 1); + } + + if (a != 0) + { + number[i] = b / a; + result[i] = '(' + y + '/' + x + ')'; + F(n - 1); + } + + // if the result is not 24, make the numbers back + number[i] = a; + number[j] = b; + result[i] = x; + result[j] = y; + } + } + } +}; + +int main(int argc, char **argv) +{ + Game24 game1; + game1.startgame(); return 0; -} \ No newline at end of file +}