Domanda

This is similar to Calculating dates given two dates excluding weekend but a different problem.

The question is "I was given a task N weekdays ago. How many days ago was this?"

On a Friday, 3 weekdays ago is 3 days ago. On a Monday, 3 weekdays ago is 5 days ago.

I can write a very simple solution by iterating. However, it strikes me that it should be possible to do this as an O(1) operation. A close but wrong answer is N + (7/5)N. Any tips?

È stato utile?

Soluzione

First convert even numbers of 5 days into 7 day weeks, then handle the remainder by adding two days if it will go over a weekend.

int MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 4, FRIDAY = 5;
int today = getToday();
int weeks = weekdays / 5;
int extraDays = weekdays % 5;
int days = weeks * 7;
if (today <= extraDays) {
    days += 2;
}
days += extraDays;

Altri suggerimenti

This should work

 static int days(int weekdays){
      int nweeks = weekdays/5;
      int extra = weekdays%5;
      int[] daysPerWeekday = new int[]{<Something based on which day it is>};
      return nweeks*7 + daysPerWeekday[extra];
 }

(I didn't include the daysPerWeekday because it seemed like you had it ("On a Friday, 3 weekdays ago is 3 days ago. On a Monday, 3 weekdays ago is 5 days ago.")...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top