Warning: Undefined array key "goal" in /home/public/projects/datemath/index.php on line 20

Deprecated: htmlentities(): Passing null to parameter #1 ($string) of type string is deprecated in /home/public/projects/datemath/index.php on line 20


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){
      eval("\$solution = $statement;");
      if($solution == $goal)
        printf("<div class=\"solution\">%s = %s</div>", $statement, $solution);
      foreach(array("", "+", "-", "*", "/") as $op)
        evalMath($statement . $op . $remaining[0], substr($remaining, 1), $goal);


The value the statements should evaluate to:

Results for 2023

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

1+2*3+4*567*8/9 = 2023