Skip to content

Instantly share code, notes, and snippets.

@Quebecisnice
Forked from fedelebron/24.cpp
Created April 9, 2012 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Quebecisnice/2345041 to your computer and use it in GitHub Desktop.
Save Quebecisnice/2345041 to your computer and use it in GitHub Desktop.
24 solver, with no access to binary_function or function<...>, thanks to an outdated compiler. :) Still using C++11 though.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#define forn(i, n) for(int i = 0; i < (n); ++i)
#define FUNC(i) (*(dispatch[funcs[i]]))
#define MFUNC(o) ([](double a, double b) { return a o b; })
using namespace std;
typedef double (*oper) (double, double);
vector<oper> dispatch;
char ops[4] = {'+', '-', '*', '/'};
double t1(vector<double> num, vector<int> funcs) {
return FUNC(0)(num[0], FUNC(1)(num[1], FUNC(2)(num[2], num[3])));
}
double t1m(vector<double> num, vector<int> funcs) {
return FUNC(2)(FUNC(1)(FUNC(0)(num[0], num[1]), num[2]), num[3]);
}
double t2(vector<double> num, vector<int> funcs) {
return FUNC(0)(num[0], FUNC(2)(FUNC(1)(num[1], num[2]), num[3]));
}
double t2m(vector<double> num, vector<int> funcs) {
return FUNC(2)(FUNC(0)(num[0], FUNC(1)(num[1], num[2])), num[3]);
}
double t3(vector<double> num, vector<int> funcs) {
return FUNC(1)(FUNC(0)(num[0], num[1]), FUNC(1)(num[2], num[3]));
}
int main() {
dispatch.push_back(MFUNC(+));
dispatch.push_back(MFUNC(-));
dispatch.push_back(MFUNC(*));
dispatch.push_back(MFUNC(/));
double epsilon = 1e-5;
vector<double> ns(4);
forn(i, 4) cin >> ns[i];
sort(ns.begin(), ns.end());
do {
forn(i, 4) forn(j, 4) forn(k, 4) {
vector<int> fs(3);
fs[0] = i;
fs[1] = j;
fs[2] = k;
if(fabs(t1(ns, fs) - 24.0) < epsilon) {
cout << ns[0] << " " << ops[fs[0]] << " ( " << ns[1] << " " << ops[fs[1]] << " ( " << ns[2] << " " << ops[fs[2]] << " " << ns[3] << " ) )" << endl;
}
if(fabs(t1m(ns, fs) - 24.0) < epsilon) {
cout << "( ( " << ns[0] << " " << ops[fs[0]] << " " << ns[1] << " ) " << ops[fs[1]] << " " << ns[2] << " ) " << ops[fs[2]] << " " << ns[3] << endl;
}
if(fabs(t2(ns, fs) - 24.0) < epsilon) {
cout << ns[0] << " " << ops[fs[0]] << " ( ( " << ns[1] << " " << ops[fs[1]] << " " << ns[2] << " ) " << ops[fs[2]] << " " << ns[3] << " ) " << endl;
}
if(fabs(t2m(ns, fs) - 24.0) < epsilon) {
cout << "( " << ns[0] << " " << ops[fs[0]] << " ( " << ns[1] << " " << ops[fs[1]] << " " << ns[2] << " ) ) " << ops[fs[2]] << " " << ns[3] << endl;
}
if(fabs(t3(ns, fs) - 24.0) < epsilon) {
cout << "( " << ns[0] << " " << ops[fs[0]] << " " << ns[1] << " ) " << ops[fs[1]] << " ( " << ns[2] << " " << ops[fs[2]] << " " << ns[3] << " ) " << endl;
}
}
} while(next_permutation(ns.begin(), ns.end()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment