Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Given the next set of week of days as strings in the given order: <code>Mon, Tue, Wed, Thu, Fri, Sat, Sun</code> <br/>
- * and given a positive integer <code>K</code> in the range <code>[0..500]</code>. <br/>
- * Find the week of day for a given day plus K days.<br/>
- * For example:<br/>
- * <code>Wed + 5 = Mon</code>
- * <code>Sun + 0 = Sun</code>
- * <code>Tue + 28 = Tue</code>
- * <br/><br/>
- * Max time for resolution: 15 minutes.
- */
- class WeekOfDayNextToK {
- private int daysOfWeekCount = 7;
- private String[] daysOfWeek = new String[] { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
- public static void main(String[] args) {
- WeekOfDayNextToK solution = new WeekOfDayNextToK();
- System.out.println(solution.solution("Wed", 5)); // Mon
- System.out.println(solution.solution("Sun", 0)); // Sun
- System.out.println(solution.solution("Tue", 28)); // Tue
- }
- public String solution(String S, int K) {
- // find index of S
- int indexOfS = getIndexForDay(S, daysOfWeek);
- // apply module over K to get the offset
- int indexForSPlusK = (indexOfS + K) % daysOfWeekCount;
- return daysOfWeek[indexForSPlusK];
- }
- private int getIndexForDay(String S, String[] daysOfWeek) {
- for (int i=0, c=daysOfWeek.length; i < c; ++i) {
- if (daysOfWeek[i].equals(S)) {
- return i;
- }
- }
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement