phparrayssum

Fill array with numbers adding up to a nominated total without exceeding item maximum


I need to fill an array with numbers, a few examples:

I tried to resolve this but I don't know the perfect solution:

function chargement($nbre, $nbreParChargement) {
    $niveaux = array();
    for($i=0; $i<=$nbre; $i++){
        $niveaux[$i] = $i + $nbreParChargement;         
    }
}

Solution

  • Another implementation, with two lines of code, for php >= 5.6:

    function chargement($nbre, $nbreParChargement){
        $niveaux = array_fill(0, floor($nbre/$nbreParChargement), $nbreParChargement);
        $niveaux[] = $nbre - array_sum($niveaux);
    
        return $niveaux;
    }
    
    var_dump(chargement(10, 4));
    var_dump(chargement(14, 6));
    var_dump(chargement(13, 16));
    var_dump(chargement(30, 4));
    

    array_fill fills an array with $nbre/$nbreParChargement entries with $nbreParChargement's value. The last value are the difference between $nbre and the sum of the other elements, given by $nbreParChargement * floor($nbre/$nbreParChargement), that will be always > 0.

    Demo.

    This work only for php >= 5.6 because array_fill accepts 0 as num only from that version. Previously, num was required to be greater than zero.

    So, for any version of php:

    function chargement($nbre, $nbreParChargement){
        $niveaux = array();
        if ($n = floor($nbre/$nbreParChargement)) {
            $niveaux = array_fill(0, $n, $nbreParChargement);
        }
    
        $niveaux[] = $nbre - array_sum($niveaux);
        return $niveaux;
    }
    

    Demo.