fork download
  1. // Joris Dauphin
  2.  
  3. #include <iostream>
  4. #include <functional>
  5. #include <vector>
  6. #include <cmath>
  7.  
  8. bool increment(std::vector<int>& v, int maxSize)
  9. {
  10. for (auto it = v.rbegin(); it != v.rend(); ++it) {
  11. ++*it;
  12. if (*it != maxSize) {
  13. return true;
  14. }
  15. *it = 0;
  16. }
  17. return false;
  18. }
  19.  
  20. void display(const std::vector<double>& operands, const std::vector<int>& operators, double total)
  21. {
  22. const char operators_string[] = "+-*/^%";
  23.  
  24. std::cout << operands[0];
  25. for (std::size_t i = 0; i != operators.size(); ++i) {
  26. std::cout << " " << operators_string[operators[i]] << " " << operands[i + 1];
  27. }
  28. std::cout << " = " << total << std::endl;
  29. }
  30.  
  31. double compute(const std::vector<double>& operands, const std::vector<int>& operators)
  32. {
  33. std::function<double(double, double)> fs[] = {
  34. [](double a, double b) { return a + b; },
  35. [](double a, double b) { return a - b; },
  36. [](double a, double b) { return a * b; },
  37. [](double a, double b) { return a / b; },
  38. [](double a, double b) { return pow(a, b); },
  39. [](double a, double b) { return fmod(a, b); },
  40. };
  41.  
  42. double res = operands[0];
  43. for (std::size_t i = 0; i != operators.size(); ++i) {
  44. res = fs[operators[i]](res, operands[i + 1]);
  45. }
  46. return res;
  47. }
  48.  
  49. void display_combinaison(const std::vector<double>& operands, double total)
  50. {
  51. std::vector<int> operators(operands.size() - 1);
  52.  
  53. do {
  54. if (compute(operands, operators) == total) {
  55. display(operands, operators, total);
  56. }
  57. } while (increment(operators, 6));
  58. }
  59.  
  60. int main()
  61. {
  62. display_combinaison({1, 2, 3, 4}, 4);
  63. display_combinaison({3, 5}, 15);
  64. }
  65.  
  66.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
1 + 2 - 3 + 4 = 4
1 + 2 / 3 * 4 = 4
1 + 2 % 3 + 4 = 4
1 * 2 ^ 3 - 4 = 4
1 ^ 2 ^ 3 * 4 = 4
1 ^ 2 % 3 * 4 = 4
1 % 2 ^ 3 * 4 = 4
1 % 2 % 3 * 4 = 4
3 * 5 = 15