samuel toh samuel toh - 4 months ago 15
PHP Question

How to make Triangle Roll-Up with PHP?

I found a question on google like this :

When given the input : 4, 7, 3, 6, 7

The output like this :

81

40 41

21 19 22

11 10 9 13

4 7 3 6 7


I can only try like the this :

for($i = 1; $i<=5;$i++){
for($j=0; $j<$i; $j++){
echo "4";
}
echo "<br/>";
}


The next I'm confused

Any solution to solve my problem?

Answer
<?php

$input = array(4, 7, 3, 6, 7);
$lines = rollup($input);

function rollup ($input) {
    $return = array();
    $line = array();
    if (count($input) > 0) {
        foreach ($input as $k=>$v) {
            if (isset($input[$k+1]))
                $line[] = $v + $input[$k+1];
        }
        $return = implode(' ', $input);
        rollup($line);
    }
    if (!empty($return))
        echo $return . '<br />';
}

?>