Integer division

Asked

Viewed 83 times

3

hello, I want to do a calculation like:

I want to distribute for example 6 integers in another 5 numbers starting at 0 with something like this: 2 1 1 1

or for example 3 integers in 5 numbers starting from zero:

1 1 0 0

My progress was something like:

<?php
$t = 5;
$i = 0;
$b = 0;
$numeros = array (
0,0,0,0
);
for($i; $i <= count($numeros)-1; $i++):

    for($b = $numeros[$i]; $b <= count($numeros)-1; $numeros[$i]++):

        $t--;
    endfor;
endfor;
echo "<br />";
echo $numeros[0];
?>
  • 1

    Enter the code you have already done to make the question more explicit

1 answer

3


If I understand your question correctly, I think this is what you’re looking for:

<?php

function distribui_inteiros($numero, $caixas) {
    echo "Distribuindo o número:  $numero em $caixas caixas.";
    $div = floor($numero / $caixas);
    $sobra = $numero - ($caixas * $div);

    for ($i = 1; $i <= $caixas; $i++) {
        $caixa[$i] = $div;
        if($sobra > 0){
            $caixa[$i]++;
        }
        $sobra--;
    }
    echo '<pre>';
    print_r($caixa);
    echo '</pre>';
    return $caixa;
}

$resultado1 = distribui_inteiros(6, 5);
$resultado2 = distribui_inteiros(3, 5);
$resultado3 = distribui_inteiros(23, 6);

The result is as follows:

Distribuindo o número: 6 em 5 caixas.
Array
(
    [1] => 2
    [2] => 1
    [3] => 1
    [4] => 1
    [5] => 1
)
Distribuindo o número: 3 em 5 caixas.
Array
(
    [1] => 1
    [2] => 1
    [3] => 1
    [4] => 0
    [5] => 0
)
Distribuindo o número: 23 em 6 caixas.
Array
(
    [1] => 4
    [2] => 4
    [3] => 4
    [4] => 4
    [5] => 4
    [6] => 3
)

If this answer helped you, I am grateful if you choose my answer and/or mark it as useful (+1). Thank you!

  • po, was that right worth mlk :)

  • There’s an error still... wait a little while I upgrade to the correct version!

  • Script fixed and updated! Good luck!

  • thanks, I’m learning all here what you did rsrsrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.