Fun With Arithmetic

July 16, 2010 By: erik Category: Geeky, Math 247 views

Rate this post:
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

Solutions to Friday Puzzle by Goal ValueI’m an avid reader of Richard Wiseman’s blog, and I find his Friday Puzzles to be particularly fun. Today’s puzzle is as follows:

How can you place the arithmetical signs ‘+’ and ‘-’ between the consecutive numbers 123456789 so that the end result is 100? So, for example, you could go…..

12+34+56-7-89 , but that would make 6, so that doesn’t work.

Try to come up with the method that uses the least number of symbols.


My first thought was, “It would be so easy to write a program to try all the possibilities!” So I did. Thirty minutes and 41 lines of javascript code later, I had this:

How many digits?
Goal Value

Charting Number of Solutions

Once I had the code to quickly generate the solutions for any arbitrary goal value, I decided to see if there was a pattern in the number of solutions between the goal values from 1 to 100. There isn't.

Solutions to Friday Puzzle by Goal Value

Click to see large.

The Code

It's just a matter of changing the operation in each slot between nothing, + and -, and when you roll back to nothing, you increment the next slot. Javascript's built in eval() function came in very handy to calculate the value of each equation.

function test() {
  function next(slots, operations) {
    for (var i = 0; i < slots.length; i++) {
      if (!slots[i]) {
        slots[i] = operations[0];
        return slots;
      }
      else {
        var index = operations.indexOf(slots[i]);
        if (index + 1 < operations.length) {
          slots[i] = operations[index + 1];
          return slots;
        }
        else
          delete slots[i];
      }
    }
    return null;
  }
  function makeEquation(slots) {
    equation = ['1'];
    for (var i = 0; i < slots.length; i++) {
      if (slots[i])
        equation.push(' ' + slots[i] + ' ');
      equation.push(i + 2);
    }
    return equation.join('');
  }
  var resultsList = document.getElementById('resultsList');
  if (resultsList)
    resultsList.remove();
  var operations = ['+', '-'];
  var slots = new Array(document.getElementById('numDigits').value - 1);
  var goalValue = document.getElementById('goalValue').value;
  while (slots != null) {
    var equation = makeEquation(slots);
    if (eval(equation) == goalValue)
      printResult(equation + ' = ' + goalValue);
    slots = next(slots, operations);
  }
}

 
  • Wolf Martinus

    Here’s my take on it (in Java)

    public class FridayPuzzle {
    
        static int calc (String s) {
            String[] parts = s.split("[+-]");
            int[] vals = new int[parts.length];
            char[] ops =  new char[parts.length];
            int pos=0, cnt = 0;
            for (String part : parts) {
                pos += part.length();
                vals[cnt] = Integer.parseInt(part);
                if (pos < s.length())
                    ops[cnt] = s.charAt(pos++);
                cnt++;
            }
            int result = vals[0];
            for (int i = 1; i < vals.length; i++) {
                switch (ops[i-1]) {
                    case '+':
                        result += vals[i];
                        break;
                    case '-':
                        result -= vals[i];
                        break;
                }
            }
            return result;
        }
    
        static void testAndMutate(String p, String m) {
            String t = p+m;
            int val = calc(t);
            if (val == 100)
                System.out.println(t+" = " +val);
            while (m.length() > 0) {
                char c = m.charAt(0);
                m = m.substring(1);
                if (!p.isEmpty()) {
                    testAndMutate(p+"+"+c, m);
                    testAndMutate(p+"-"+c, m);
                }
                p +=c;
            }
        }
    
        public static void main(String[] args) {
            String start = "123456789";
            testAndMutate("", start);
        }
    }
    • http://www.erik-rasmussen.com/ Erik R.

      Yeah, avoiding the grotesqueness of the calc method is what makes the program a lot cleaner in javascript or python where you can just call eval(). You end up spending the majority of the code just trying to sum up a string of numbers and operators. Java, my primary programming language, can be awfully awkward sometimes.

      • Wolf Martinus

        I agree, there’s probably (no certainly) a library out there that does a good eval(…) job.
        Also the sollution was Q&D and not aiming for elegance.

        A slightly nicer variant would be:

        static int calc(String s) {
        return calc(0,s);
        }

        static int calc (int val, String s) {
        if (s.isEmpty()) return 0;
        char c = s.charAt(0);
        s = s.substring(1);
        switch (c) {
        case ‘+':
        val += calc(s);
        break;
        case ‘-‘:
        val -= calc(s);
        break;
        default:
        val = calc (val * 10 + (c-‘0′), s);
        }
        return val;
        }