我正在努力寻找一种有效而清晰的算法来解决以下问题。我特意在javascript中工作,但这确实是一个非常普遍的问题。
我每天都有一家商店开放数小时 太阳:关闭 星期一:7a-6p 周二:7a-6p ...
每天可以有不同的营业时间,有些日子可能完全关闭。
如果此商店的工作需要一定的时间,并且只在其工作时间内有效。我怎样才能计算出最早的时间?一些考虑因素,一些工作可能需要超过一周的工作时间来完成,商店可能会选择在更随机的时间关闭,6:03。
答案 0 :(得分:0)
也许是这样的?你需要有很长的工作才能导致任何性能问题。
var timeToFinish = getTimeToFinish(job);
var timeLeft = timeToFinish;
var date = getStartingDate(job);
while(timeLeft > 0){
var workingHours = getWorkingHours(day);
if(timeLeft > workingHours){
timeLeft -= workingHours;
date = nextDay(date);
} else {
timeLeft == 0;
}
}
return date;
函数getWorkingHours(day)
可能会查询具有开放时间表的数据库。
答案 1 :(得分:0)
/**
* @param hoursOfWork a non-negative number of hours required to complete
* a project.
* @param openHours A list of length 7 of lists of ranges of
* inclusive hours in the range [0-23].
* For a particular day of the week,
* open 9-5 is represented by [[9,17]],
* and closed-for-the-day is represented by [],
* and open 9-12 and 1-5 is represented by [[9, 12], [13, 17]].
* @param startDayOfWeek is an integer in the range [0, 6] of the first
* day of the week on which work occurs.
*/
function daysRequired(hoursOfWork, startDayOfWeek, openHours) {
var daysInWeek = 7; // Vive la revolution (but not metric weeks).
// Make sure they're open sometime during the week so we don't infinitely loop.
var totalForWeek = 0;
var totalsForDay = [];
for (var i = 0; i < daysInWeek; ++i) {
var hoursOfWorkInDay = hoursOfWork[i];
var totalForDay = 0;
for (var j = 0, n = hoursOfWorkInDay.length; j < n; ++j) {
totalForDay += (hoursOfWorkInDay[j][1] - hoursOfWorkInDay[j][0]);
}
totalForWeek += totalForDay;
totalsForDay[i] = totalForDay;
}
if (totalForWeek < 1) { throw new Error('work harder'); }
if (hoursOfWork !== hoursOfWork || !isFinite(hoursOfWork)) {
throw new Error('' + hoursOfWork);
}
// Step forward by days subtracting each days work hours from the total.
var daysRequired = 0;
var dayOfWeek = startDayOfWeek;
while (hoursOfWork > 0) {
++daysRequired; // Count the day since we have to do some work on it.
var totalForDay = totalsForDay[dayOfWeek];
if (totalForDay >= hoursOfWork) { break; }
hoursOfWork -= totalForDay; // Work that day.
dayOfWeek = (dayOfWeek + 1) % daysInWeek; // Skip to next day of week.
}
return daysRequired;
}