tags:

views:

96

answers:

3

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 probably figure it out in a hacky way, but I'm hoping to learn something from it as well :P

The language used is PHP.

A: 

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

Henrik
+2  A: 
//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));
}
Oliver
note that $days and $items are both just counts of how many days and items there are. I accidentally typed "days" instead of "items" in the for loop, but fixed that in an edit. the floor() function just removes any decimal places.
Oliver
A: 

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
dnagirl
I'm not sure which of the approach would have worked the best, but I went with this one, thank you :)
Marco
Oliver's approach is more efficient as it doesn't require 2 different methods. This solution is less elegant, but perhaps more immediately understandable.
dnagirl