How to make Triangle Roll-Up with PHP?

后端 未结 4 389
借酒劲吻你
借酒劲吻你 2020-12-07 04:53

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          


        
4条回答
  •  孤街浪徒
    2020-12-07 05:29

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

     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";
        });
    ?>
    

    See it working here

提交回复
热议问题