I will assign 8 days off to a crew randomly in a calendar month.
I would like to randomly choose 8 days, and the days off distribution should be as even as possible. I mean all 8 days-off shouldn’t be gathered in first 8 days of the month, for example.
For example: [1, 5, 8, 14, 18, 24, 27, 30] is a good distribution.
[1,2,3,4,26,27,28,29] is not a good distribution.
Actually, a crew can’t work 7 consecutive days. In every 7 days, there must be 1 day-off.
All days are treated equally, ie Sundays are not days-off by themselves. Crew may work on weekends as well.
I want to choose days-off one by one. Not 8 of them together at once.
Could you recommend an algorithm using python to achieve this?
Not all days in the month may be available to be days off.
Best Regards
This is the key here:
Actually, a crew can't work 7 consecutive days. In every 7 days, there must be 1 day-off.Reword the problem to say a random 2 days in every 7 days (or divide the month into four lengths of time as appropriate). You are then guaranteed an even-ish distribution. Use
random.sample()as Martijn Pieters suggests.You can generate two values using this technique from the first week, then yield them in sequence if you want them one by one.
edit:
As observed by tcaswell, there are still some cases where you end up with ten days in a row on duty. To combat this, you can assign a day off every three days, create a list of ten, and remove two days at random from the subset of days that don’t invalidate the 7-continuous-day criteria.
Alternatively, you could just keep generating lists using the original algorithm until it fits the criteria, since you’re very likely to get a valid solution anyway. You’d have to write a validation function of some kind, but it would be very easy to do since you’re just counting the longest continuous string of days on.
CODE:
An implementation of the second option.