Archive for June, 2008

Simple Fours Problem

Wednesday, June 18th, 2008

My mom sent me this simple problem.Combine four fours arithmetically (i.e. 4 / 4 – 4 * 4) so the result is 20. The following solution is written in C++ and uses brute force to find all possible solutions:

/*
 *  combo.cxx - Four Fours Combination Problem Solver
 *              (using brute force)
 *
 *  Solves the simple problem: How do you combine four fours 
 *       using standard arithmetic operations to equal 20.
 *
 *  This program solves this puzzle using brute force and 
 *       shows the answer ignoring order of operations.
 *
 *
 *  Sumit Khanna / http://penguindreams.org
 *    free to modify and redistribute
 */

#include <iostream>
using std::cout;
using std::endl;

int doOp(char op, int a,int b) {
  if(op == '+') {
    return a + b;
  }
  else if(op == '-') {
    return a - b;
  }
  else if(op == '*') {
    return a * b;
  }
  else if(op == '/') {
    return a / b;
  }
  else {
    cout << "Error. Invalid Operation " << op << endl;
    exit(2);
    return 0;
  }
}

int main(int argc, char **argv) {

 char *ops = new char[4];
 ops[0] =  '+';
 ops[1] =  '-';
 ops[2] =  '*';
 ops[3] =  '/';

 for(int i=0; i<4; i++) {
   for(int j=0; j<4; j++) {
     for(int k=0; k<4; k++) {

          int r = doOp(ops[i],4,4); 
          r = doOp(ops[j],r,4);
          r = doOp(ops[k],r,4);

          if(r == 20) {
            cout << " 4 " << ops[i] << " 4 " << ops[j] << " 4 " << ops[k] << " 4 = 20 " <<  endl;
          }

     }
   }
 }
 
 cout << "Note: Solutions ignores order of operations" << endl << endl; 

 delete[] ops;
 exit(0);

}

Scripts

Monday, June 16th, 2008

I’ve added a new Scripts section to the website. It contains several shell scripts I’ve written over the years for automating basic tasks on my Linux machines including Gentoo Package Updating, lnSponge which keeps track of new files in a given directory tree, and an Email Script which will e-mail the standard output of an application. Expect more scripts to be posted in the near future.