It's not really 10 lines and not really a function but someone asked for a solver to enigmatic calculus, i.e. find the digits to assign to letters to have a meaningful system:
ab + acd = aec
e * da = bfg
dge + bg = chi
ab * e = dge
acd / da = bg
aec - bfg = chi
The solution was:
#include <list>
#include <cmath>
#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <ext/numeric>
#include <iterator>
#include <functional>
#include <boost/bind.hpp>
using namespace std;
static const int fact_10 = 3628800;
static const int tenpowers[] = {1, 10, 100, 1000, 10000 /*, ... */ };
struct equation {
struct valorize {
int s; const vector<int>& idx_m;
valorize(const vector<int>&idx) : s(0), idx_m(idx) { }
int operator()(int tot, char b) { return tot+idx_m[b-'a']*tenpowers[s++]; }
};
int operator()(const vector<int>& idx) const {
int opa=accumulate(opa_m.rbegin(), opa_m.rend(), 0, valorize(idx));
int opb=accumulate(opb_m.rbegin(), opb_m.rend(), 0, valorize(idx));
int res=accumulate(res_m.rbegin(), res_m.rend(), 0, valorize(idx));
switch(operator_m) {
case '+': return abs(opa+opb-res);
case '-': return abs(opa-opb-res);
case '*': return abs(opa*opb-res);
case '/': return abs(opa-opb*res);
}
}
friend istream& operator>>(istream& in, equation& e) { char dummy;
return in >> e.opa_m >> e.operator_m >> e.opb_m >> dummy >> e.res_m; }
protected:
string opa_m, opb_m, res_m;
char operator_m;
};
int main(int argc, char* argv[]) {
if(argc != 2) { cerr << "ces file.dat" << endl; return 1; }
vector<equation> eqns; ifstream dat(argv[1]);
if(dat) copy(istream_iterator<equation>(dat), istream_iterator<equation>(),
back_inserter(eqns));
else { cerr << "can't open " << argv[1] << endl; return 1; }
vector<int> x(10); iota(x.begin(), x.end(), 0);
typedef list< vector<int> > sol_list;
sol_list solutions;
for(int ii(0); ii != fact_10; ++ii) {
if(!accumulate(eqns.begin(),eqns.end(),0,boost::bind(std::plus<int>(),_1,
boost::bind(&equation::operator(), _2, boost::ref(x)))))
solutions.push_back(x);
next_permutation(x.begin(), x.end());
}
for(sol_list::iterator si = solutions.begin(); si!= solutions.end(); ++si)
copy(si->begin(), si->end(), ostream_iterator<int>(cout << endl, " "));
cout << endl;
}
Ah, wait... it was about elegance!