Procedural

After having worked out a numerical expression for 2016 yesterday from the digits 1…9 just by intuition, and then seeing Paul’s very cool count-down version, I decided, true to one of my recent posts in these pages, to write a program.

The required code turned out to be surprisingly small. The below Javascript program computes 1…9 arithmetic expressions for the years 2000 through 2030, in all cases that use at most a + – or * between the digits.

for (year = 2000 ; year <= 2030 ; year++)
for (N = 1 << 16 ; N ; N--) {
   s = '1';
   for (i = 2 ; i <= 9 ; i++)
      s += (n = N >> 2*i-4 & 3) ? (n<2 ? '+' : n<3 ? '-' : '*') + i : i; 
   if (year == eval(s))
      console.log(year + ' ' + s);
}

A small variation in this program would generate all the "count-down" versions. Interestingly, it turns out that there are just about twice as many count-up solutions as count-down solutions.

Doing this exercise made me realize that what I really want is a programming language that would let me describe such patterns very simply, and then ask questions like: "Which of those patterns adds to 2016?"

Leave a Reply

Your email address will not be published. Required fields are marked *