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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

<?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 />';
}

?>

Solution 2

You can use this code

<?php
$arr = [4, 7, 3, 6, 7];
$count = count($arr);
$finalStr = "";
while($count>0){
  $str = "";
  foreach($arr as $key=>$val){
    $arr[$key] = $arr[$key]+$arr[$key+1];
    $str .="$val  ";
  }
  $str .= "\n";
  $finalStr = $str . $finalStr;
  unset($arr[count($arr)-1]);

  $count--;
}
echo $finalStr;
?>

Check live demo : https://eval.in/609908

Output is :

81  
40  41  
21  19  22  
11  10  9  13  
4  7  3  6  7  

Solution 3

Try this,

<?php 
$a = 4;
$b = 7;
$c = 3;
$d = 6;
$e = 7;
for($y = 1; $y<=5;$y++){
    for($z=0; $z<$y; $z++){
        $f = $a+$b;
        $g = $b+$c;
        $h = $c+$d;
        $i = $d+$e;
        $j = $f+$g;
        $k = $g+$h;
        $l = $h+$i;
        $m = $j+$k;
        $n = $k+$l;
        $o = $m+$n;
    }
}
echo $o.'<br/>';
echo $m.' '.$n.'<br/>';
echo $j.' '.$k.' '.$l.'<br/>';
echo $f.' '.$g.' '.$h.' '.$i.'<br/>';
echo $a.''.$b.' '.$c.' '.$d.' '.$e;
?>

Solution 4

Just to give another solution, because I like ‘puzzlers’ like these, I’ll give you this:

<pre>
<?php
    //init
    $input  = [4, 7, 3, 6, 7];
    $output = [$input];

    //process
    while(count($input) > 1) {
        foreach($input as $key => $val) {
            $key ? $input[] = $val + $prev : $input = array();
            $prev = $val;       
        }
        array_unshift($output, $input);
    }

    //output    
    array_walk($output, function($line){
        echo implode(' ', $line) . "\n";
    });
?>
</pre>

See it working here

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply