Problem

From Coding Horror - The Nonprogramming Programmer comments

You have the numbers 123456789, in that order. Between each number, you must insert either nothing, a plus sign, or a multiplication sign, so that the resulting expression equals 2001. Write a program that prints all solutions.

Solution (PHP)


  $numbers = "123456789";
  $goal = 2001;
  evalMath($numbers[0], substr($numbers, 1), $goal);
  
  function evalMath($statement, $remaining, $goal){
    if(empty($remaining)){
      eval("\$solution = $statement;");
      if($solution == $goal)
        printf("<div class=\"solution\">%s = %s</div>", $statement, $solution);
    }
    else
      foreach(array("", "+", "-", "*", "/") as $op)
        evalMath($statement . $op . $remaining[0], substr($remaining, 1), $goal);
  }
  

Example

The value the statements should evaluate to:

Results for 2018

(It might take a minute. Be patient. Some values have no answers.)

12*34*5+67-89 = 2018
1-2+3+4*567*8/9 = 2018
1-2+3/4*5*67*8+9 = 2018
1*2345-6*7*8+9 = 2018