Robson » Code » PHP » Number Pyramid Max Route

 
<?
   // number pyramid max route v1.0
 
   // example pyramid
   $triangle = '
17
23 45
97 82 14
42 28 34 68';
 
   $lines = explode(chr(13) . chr(10), $triangle);
   foreach($lines as &$line)
       $line = explode(' ', $line);
       
   for ($n = count($lines)-2; $n > 0; $n--)
       for ($a = 0; $a < count($lines[$n]); $a++)
           // to find the minimum path, remove the exclamation mark
           $lines[$n][$a] += $lines[$n+1][$a + !($lines[$n+1][$a] > $lines[$n+1][$a+1])];
   echo $lines[1][0];
?>
 
© 2004-17 robson | cc unless stated