开发者

Evenly distribute values over a time period

开发者 https://www.devze.com 2022-12-11 21:25 出处:网络
I have got a variable amount of items, and a variable date range that I need to distribute them over. Lets say I have 3 items and I need to distribute them over 6 days. What I would want is to have ev

I have got a variable amount of items, and a variable date range that I need to distribute them over. Lets say I have 3 items and I need to distribute them over 6 days. What I would want is to have every second day have an item, and it does not matter if the first day has an item or not. If I had 7 items over 6 days, one of the days would get 2 items, it does not matter which day that is either.

Sadly, it turns out I really suck at maths, so I have no real idea on how to do this in a relatively nice and pretty way, or if it is even possible. I could pr开发者_StackOverflow社区obably figure it out in a hacky way, but I'm hoping to learn something from it as well :P

The language used is PHP.


//If you get the period between items:
$period = $days / $items;
//Then you can iterate through the items:
for ($i = 0; $i < $items; $i++)
{
    //and have a function that will add an item to the day number given as a parameter.
    add_item_to_day_number(floor($i * $period));
}


Essentially you're doing division and then distributing the remainder sequentially. So the steps go something like this:

  • count the number of days
  • count the number of items

  • if items > days

    • divide the number of items by the number of days (items per day) $x
    • take the modulus of items/day $m (this is the remainder)
    • cycle through the days placing $x items on each day, and 1 extra item on the first $m days
  • if days > items

    • divide the number of days by the number of items (days per item) $x
    • cycle through the days stepping by $x and placing 1 item on each day (keep track of how many items are left)
    • when you arrive past the last day, if there are any items left, loop over the days again starting at day0+1 and stepping by $x


(items in day i) = floor( (i+1) * items / days) - floor( i * items / days), where i is 0-based.

0

精彩评论

暂无评论...
验证码 换一张
取 消