Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- namespace prob21 {
- typedef double(*Func)(double,double);
- double add(double a, double b){return a+b;}
- double sub(double a, double b){return a-b;}
- double mul(double a, double b){return a*b;}
- double div(double a, double b){return a/b;}
- bool eq(double a, double b)
- {
- return std::abs(a-b) < 0.01;
- }
- const Func funcs[4] = {add, sub, mul, div};
- const char funcNames[4] = {'+', '-', '*', '/'};
- const int vals[6] = {1,2,3,4,5,6};
- const double target = 35;
- char path[5];
- void print(double acc)
- {
- for (int i=0; i<5; ++i)
- std::cout << '(';
- std::cout << vals[0];
- for (int i=1; i<6; ++i)
- std::cout << path[i-1] << vals[i] << ')';
- std::cout << '=' << acc << std::endl;
- }
- void dig(int ind, double acc)
- {
- if (ind==5) {
- if (eq(acc, target))
- print(acc);
- return;
- }
- for (int i=0; i<4; ++i) {
- path[ind] = funcNames[i];
- Func f = funcs[i];
- double v = vals[ind+1];
- dig(ind+1, f(acc, v));
- }
- }
- void solve()
- {
- dig(0, vals[0]);
- }
- }
- int main()
- {
- prob21::solve();
- return 0;
- }
Add Comment
Please, Sign In to add comment