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,
Approach: There is always a way of splitting the number if X >= N. If the number is being split into exactly 'N' parts then every part will have the value X/N and the remaining X%N part can be distributed among any X%N numbers.
Function divideN(int n) takes n and returns the number of ways in which n can be divided into 3 parts. Take the initial variable count as 0 for the number of ways. Traverse using three for loops for each part of the number. Outermost loop from 1<=i<n, inner loop i<=j<n , innermost j<=k<n.
To split a number into integer and decimal parts: Use floor division to get the integer part of the number by dividing by 1 , e.g. num // 1 . Use the modulo % operator to get the fractional part by getting the remainder after dividing by 1 , e.g. num % 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
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);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With