Created
October 2, 2019 16:35
-
-
Save fabri1983/6022ce70ad2f9db5da6745897a24afcd to your computer and use it in GitHub Desktop.
Given a set of week days and a positive integer K, find the week of day which follows a day plus K days.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment