Advertisement
ttsiodras

Happy New Year, fellow coders

Dec 31st, 2011
2,970
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. // Happy New Year, fellow coders!
  2. // ttsiodras@gmail.com, http://users.softlab.ntua.gr/~ttsiod/
  3.  
  4. #include <iostream>
  5. #include <algorithm>
  6.  
  7. const int yearToHuntFor=2012;
  8.  
  9. int ad(int a,int b) { return a+b; }
  10. int ml(int a,int b) { return a*b; }
  11. int sb(int a,int b) { return a-b; } // negative result considered bad
  12. int dv(int a,int b) { return (a%b)?-1:a/b; } // negative result considered bad
  13. int pw(int a,int b) { int res=a; for(int i=1; i<b; i++) res*=a; return res; }
  14. int (*ops[])(int,int) = {ad,sb,ml,dv,pw};
  15. const char *opsStr[] = {"+","-","*","/","^"};
  16.  
  17. int v[] = {1,2,3,4,5,6};
  18. const int vlen = sizeof(v)/sizeof(v[0]);
  19. int opsSoFar[vlen];
  20.  
  21. void recurse(int value, int argCount)
  22. {
  23.     if (argCount>vlen-1) return;
  24.     for(int opIdx=0; opIdx<5; opIdx++) {
  25.     int result = ops[opIdx](value, v[argCount]);
  26.     if (result<0) continue; // "bad" subtraction or division
  27.     opsSoFar[argCount-1] = opIdx; // log the operation used
  28.     if (result != yearToHuntFor) {
  29.         recurse(result, argCount+1);
  30.     } else {
  31.         std::cout << "(((((" << v[0];
  32.         for(int i=1; i<vlen; i++) {
  33.         std::cout << opsStr[opsSoFar[i-1]] << v[i] << ")";
  34.         }
  35.         std::cout << "=" << result << std::endl;
  36.     }
  37.     }
  38. }
  39.  
  40. main()
  41. {
  42.     do { recurse(v[0],1); } while (std::next_permutation (v,v+vlen) );
  43.     return 0;
  44. }
  45.  
  46. // Outputs:
  47. //
  48. // ttsiod@elrond:tmp$ g++ -O3 -o 2012 2012.cpp
  49. // ttsiod@elrond:tmp$ ./2012
  50. // (((((1+4)+5)^3)+6)*2)=2012
  51. // (((((1+5)+4)^3)+6)*2)=2012
  52. // (((((4+1)+5)^3)+6)*2)=2012
  53. // (((((4+5)+1)^3)+6)*2)=2012
  54. // (((((4+6)^3)+1)+5)*2)=2012
  55. // (((((4+6)^3)+5)+1)*2)=2012
  56. // (((((5+1)+4)^3)+6)*2)=2012
  57. // (((((5+4)+1)^3)+6)*2)=2012
  58. // (((((6+4)^3)+1)+5)*2)=2012
  59. // (((((6+4)^3)+5)+1)*2)=2012
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement