Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Happy New Year, fellow coders!
- // ttsiodras@gmail.com, http://users.softlab.ntua.gr/~ttsiod/
- #include <iostream>
- #include <algorithm>
- const int yearToHuntFor=2012;
- int ad(int a,int b) { return a+b; }
- int ml(int a,int b) { return a*b; }
- int sb(int a,int b) { return a-b; } // negative result considered bad
- int dv(int a,int b) { return (a%b)?-1:a/b; } // negative result considered bad
- int pw(int a,int b) { int res=a; for(int i=1; i<b; i++) res*=a; return res; }
- int (*ops[])(int,int) = {ad,sb,ml,dv,pw};
- const char *opsStr[] = {"+","-","*","/","^"};
- int v[] = {1,2,3,4,5,6};
- const int vlen = sizeof(v)/sizeof(v[0]);
- int opsSoFar[vlen];
- void recurse(int value, int argCount)
- {
- if (argCount>vlen-1) return;
- for(int opIdx=0; opIdx<5; opIdx++) {
- int result = ops[opIdx](value, v[argCount]);
- if (result<0) continue; // "bad" subtraction or division
- opsSoFar[argCount-1] = opIdx; // log the operation used
- if (result != yearToHuntFor) {
- recurse(result, argCount+1);
- } else {
- std::cout << "(((((" << v[0];
- for(int i=1; i<vlen; i++) {
- std::cout << opsStr[opsSoFar[i-1]] << v[i] << ")";
- }
- std::cout << "=" << result << std::endl;
- }
- }
- }
- main()
- {
- do { recurse(v[0],1); } while (std::next_permutation (v,v+vlen) );
- return 0;
- }
- // Outputs:
- //
- // ttsiod@elrond:tmp$ g++ -O3 -o 2012 2012.cpp
- // ttsiod@elrond:tmp$ ./2012
- // (((((1+4)+5)^3)+6)*2)=2012
- // (((((1+5)+4)^3)+6)*2)=2012
- // (((((4+1)+5)^3)+6)*2)=2012
- // (((((4+5)+1)^3)+6)*2)=2012
- // (((((4+6)^3)+1)+5)*2)=2012
- // (((((4+6)^3)+5)+1)*2)=2012
- // (((((5+1)+4)^3)+6)*2)=2012
- // (((((5+4)+1)^3)+6)*2)=2012
- // (((((6+4)^3)+1)+5)*2)=2012
- // (((((6+4)^3)+5)+1)*2)=2012
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement