Dividing a integer equally in X parts

15,567

Solution 1

Here's the algorithm you're looking for; it evenly spreads an integer N over K cells:

for i = 0 to K
    array[i] = N / K    # integer division

# divide up the remainder
for i = 0 to N mod K
    array[i] += 1

Solution 2

Try this code

<?php
$num = 400;
$val = floor($num/24);

for($i=0;$i<24;$i++) {
    $arr[$i] = $val;
}

$arr[0] += $num - array_sum($arr);
?>
Share:
15,567
Jean-Philippe Murray
Author by

Jean-Philippe Murray

Studied religions and its people for some time, now I’m back working with the web. Passionate about technologies, the human being and the human becoming.

Updated on July 27, 2022

Comments

  • Jean-Philippe Murray
    Jean-Philippe Murray almost 2 years

    I'm looking for a efficient way in PHP to divide a number in equal part. Number will always be integer (no float).

    Let's say that I have an array $hours with values from "1" to "24" ($hours['1'], etc) and a variable $int containing an integer. What I want to acheive is spreading the value of $int equally in 24 parts so I can assing the value to each corresponding array entries. (Should the number be odd, the remaining would be added to the last or first values in the 24).

    Regards,

  • Jean-Philippe Murray
    Jean-Philippe Murray about 12 years
    There you go! I didn't for once think that I could do a for loop with the N / K operation as the condition to stop. I just learned something here, and it works marvelously ! Thank you !
  • Fred Foo
    Fred Foo about 12 years
    @Jean-PhilippeMurray: please check out the correction that Zombaya just made to my algorithm; the loop should run up to N mod K, not N / K.
  • Jean-Philippe Murray
    Jean-Philippe Murray about 12 years
    Could you just explain me what is the difference between N mod K and N / K at the end? I don't seem to see any difference while testing the two solutions...
  • Fred Foo
    Fred Foo about 12 years
    @Jean-PhilippeMurray: then your test doesn't cover all the appropriate cases. When you divide N by K, you get a remainder of N mod K and that's what you need to "smear out" over the array. In some cases, e.g. N=3 and K=2, N/K == N mod K, but not in general.