We’re hiring a new Java developer and decided to start by asking them to write code instead of the usual Q&A.
Recently we needed to add an hourly scheduler to our sliding window data aggregator and decided this would be a good test to see how people think and code.
We gave our candidates the following class skeleton to complete. As you can see, it has two parts. A constructor that takes in a variable number of minutes-past-the-hour arguments. And a method that returns the next occurrence given a fixed point in time.
We asked our candidates to compete the code and make all the tests in the main method pass.
Here’s the full listing. How would you implement it?
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import java.util.Date; /** * This class represents a fixed hourly schedule. * * It can tell you the next start time for an event after a given point in * time. * * You first define the minutes past each hour that an event can * occur (for example HH:00, HH:15, HH:30, and HH:45). Then you call * {@link #getNextTime(long)} to find the next occurrence from any point * in time. In the above scenario, passing in 4:23 PM today should return * 4:30 PM today. * */ public class HourlySchedulerTest { /** * Accepts the minutes past each hour that an event can start * (for example 0, 15, 30, and 45). * */ public HourlySchedulerTest(int ... minutesPastHour) { } /** * Returns the next start time from the given point in time. */ public long getNextTime(long fromMillis) { return ; } public static void main(String[] args) { HourlySchedulerTest test = new HourlySchedulerTest(0, 15, 30, 45); final long now = 1426708139391L; // Wed Mar 18 15:48:59 2015 expect(test, now, 1426708800000L); expect(test, now + 900000L, 1426709700000L); expect(test, now + 1800000, 1426710600000L); expect(test, now + 2700000L, 1426711500000L); expect(test, now + 3600000L, 1426712400000L); } private static void expect(HourlySchedulerTest test, long fromMillis, long expectedNextTime) { long actualNextTime = test.getNextTime(fromMillis); if (actualNextTime != expectedNextTime) { System.out.println("Test failed. Expected: " + new Date(expectedNextTime) + " (" + expectedNextTime + "), but found " + new Date(actualNextTime) + " (" + actualNextTime + ")"); } else { System.out.println("Test passed. " + new Date(actualNextTime)); } } } |
Happy coding!