### Min and Max Equations

Permutations
Algorithms
Code
Diff
• ``````#include <map>
#include <array>
#include <string>
#include <numeric> // accumulate

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;
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],
[&,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 = "+-*/";
//  No need to sort here ?
do {
results[calculate(numbers, ops)]=ops;
} while (std::next_permutation(ops.begin(), ops.end()));
return {results.begin()->second,results.rbegin()->second};
}
``````
•  1 − #include 2 − #include 3 − #include 4 − 5 − using namespace std; 6 − 7 − double add(double a, double b) { return a + b; } 8 − double sub(double a, double b) { return a - b; } 9 − double mul(double a, double b) { return a * b; } 10 − double div(double a, double b) { return a / b; } 11 − 12 − typedef double (*opFunc)(double a, double b); 13 − 14 − double calculate(array const numbers, string ops) { 15 − map const opFuncs = { 16 − {'+', add}, {'-', sub}, {'*', mul}, {'/', div}, 17 − }; 18 − double result = numbers[0]; 19 − for (int i = 0; i < 4; i++) { 20 − opFunc op = opFuncs.at(ops[i]); 21 − result = op(result, numbers[i + 1]); 22 − } 23 − return result; 24 − } 25 − 26 − pair MinMaxEquations(array const& numbers) { 27 − 28 − map results; 29 − string ops = "+-*/"; 30 − sort(ops.begin(), ops.end()); 31 − do { 32 − results[ops] = calculate(numbers, ops); 33 − } while (next_permutation(ops.begin(), ops.end())); 34 − 35 − auto [min, max] = minmax_element(results.begin(), results.end(), 36 − [](const pair& p1, const pair& p2) { 37 − return p1.second < p2.second; }); 38 − return make_pair(min->first, max->first); 39 − } 1 + #include 2 + #include 3 + #include 4 + #include // accumulate 5 + 6 + double oc(char c, double d1, double d2) { 7 + switch (c) { 8 + case '+':return d1+d2; 9 + case '-':return d1-d2; 10 + case '/':return d1/d2; 11 + case '*':return d1*d2; 12 + default: return 0.0; 13 + } 14 + // return 0.0; 15 + } 16 + 17 + double calculate(const array& nums, const string& ops) { 18 + return std::accumulate(std::next(nums.begin()),nums.end(),nums[0], 19 + [&,i=0](auto acc,auto d) mutable { 20 + return oc(ops[i++],acc,d); }); 21 + } 22 + 23 + std::pair MinMaxEquations(const array& numbers) { 24 + std::map results; // double first: insertion is sorted 25 + std::string ops = "+-*/"; 26 + // No need to sort here ? 27 + do { 28 + results[calculate(numbers, ops)]=ops; 29 + } while (std::next_permutation(ops.begin(), ops.end())); 30 + return {results.begin()->second,results.rbegin()->second}; 31 + }

Code
Diff