Ad
Permutations
Algorithms
Logic
Code
Diff
  • #include <map>
    #include <array>
    #include <string>
    #include <numeric> // accumulate
    using namespace std;
    double oc(char c, double d1, double d2) {
      switch (c) {
          case '+': return d1+d2; break;
          case '-': return d1-d2; break;
          case '/': return d1/d2; break;
          case '*': return d1*d2; break;
          default: return 0.0;
      }
    //  return 0.0;
    }
    
    double calculate(const array<int, 5>& nums, const string& ops) {
        return accumulate(next(nums.begin()),nums.end(),nums[0],
                              [&,i=0](auto acc,auto d) mutable {
                                  return oc(ops[i++],acc,d); });
    }
    
    pair<string, string> MinMaxEquations(const array<int, 5>& numbers) {
        map<double,string> results; // double first: insertion is sorted
        string ops = "+-*/";
    //  No need to sort here ?
        do {
            results[calculate(numbers, ops)]=ops;
        } while (next_permutation(ops.begin(), ops.end()));
        return {results.begin()->second,results.rbegin()->second};
    }
    
    • #include <map>
    • #include <array>
    • #include <string>
    • #include <numeric> // accumulate
    • using namespace std;
    • double oc(char c, double d1, double d2) {
    • switch (c) {
    • case '+':return d1+d2;
    • case '-':return d1-d2;
    • case '/':return d1/d2;
    • case '*':return d1*d2;
    • case '+': return d1+d2; break;
    • case '-': return d1-d2; break;
    • case '/': return d1/d2; break;
    • case '*': return d1*d2; break;
    • default: return 0.0;
    • }
    • // return 0.0;
    • }
    • double calculate(const array<int, 5>& nums, const string& ops) {
    • return std::accumulate(std::next(nums.begin()),nums.end(),nums[0],
    • return accumulate(next(nums.begin()),nums.end(),nums[0],
    • [&,i=0](auto acc,auto d) mutable {
    • return oc(ops[i++],acc,d); });
    • }
    • std::pair<std::string, std::string> MinMaxEquations(const array<int, 5>& numbers) {
    • std::map<double,string> results; // double first: insertion is sorted
    • std::string ops = "+-*/";
    • pair<string, string> MinMaxEquations(const array<int, 5>& numbers) {
    • map<double,string> results; // double first: insertion is sorted
    • string ops = "+-*/";
    • // No need to sort here ?
    • do {
    • results[calculate(numbers, ops)]=ops;
    • } while (std::next_permutation(ops.begin(), ops.end()));
    • } while (next_permutation(ops.begin(), ops.end()));
    • return {results.begin()->second,results.rbegin()->second};
    • }