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

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 2024

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

1234-5+6+789 = 2024
12*34*5-6+7-8-9 = 2024