Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing a integer equally in X parts

Tags:

php

math

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,

like image 350
Jean-Philippe Murray Avatar asked Apr 28 '12 18:04

Jean-Philippe Murray


People also ask

How do you divide a number into equal parts?

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.

How do you divide a number into equal parts in C++?

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.

How do you split a number into equal parts in Python?

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 .


2 Answers

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
like image 88
Fred Foo Avatar answered Sep 20 '22 03:09

Fred Foo


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);
?>
like image 28
Nauphal Avatar answered Sep 20 '22 03:09

Nauphal