settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Condense Array to Number - PHP Task

+2 votes

Write a program to read an array of integers and condense them by summing adjacent couples of elements until a single integer is obtained. For example, if we have 3 elements {2, 10, 3}, we sum the first two and the second two elements and obtain {2+10, 10+3} = {12, 13}, then we sum again all adjacent elements and obtain {12+13} = {25}.

Examples:

condense array to number php task

asked in PHP category by user Jolie Ann

1 Answer

+1 vote

My solution to your task:

<?php

$arr = array_map('intval', explode(' ', readline()));

while (count($arr) > 1) {
    $arrNew = [];
    for ($i = 0; $i < count($arr) - 1; $i++) {
        $arrNew[$i] = $arr[$i] + $arr[$i + 1];
    }
    $arr = $arrNew;
}

echo $arr[0];
answered by user mitko
...