Clock Time Class
Problem
A clock time has an hour and a minute (24-hour clock, it wraps after 23:59). Commands: set NAME HH:MM (store a time), add NAME MINUTES (move the time forward; it wraps past midnight), diff A B (print the minutes you must move forward from A to reach B, from 0 to 1439), show NAME (print HH:MM with two digits each).
Constraints
- 1 <= commands <= 100
- names have no spaces
- MINUTES >= 0
Examples
Input
set a 23:50 add a 20 show a
Output
00:10
Solutions
The Time object hides how the time is stored. Callers only use plus, until and text, so the wrap-around rule lives in one place.
/*
* Problem : Run the commands.
* Input : Command lines.
* Output : One line per answer.
* Approach: Time class
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: A Time keeps one number: the minutes since midnight. It never changes after it is created.
static class Time {
private final int minutes;
Time(int minutes) {
this.minutes = minutes;
}
// Step 2: Moving forward gives a new Time. The remainder makes the clock wrap.
Time plus(int extra) {
return new Time((minutes + extra) % 1440);
}
int until(Time other) {
return ((other.minutes - minutes) % 1440 + 1440) % 1440;
}
String text() {
return String.format("%02d:%02d", minutes / 60, minutes % 60);
}
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
java.util.Map<String, Time> times = new java.util.HashMap<String, Time>();
java.util.List<String> out = new java.util.ArrayList<String>();
for (String line : lines) {
String[] part = line.split(" ");
if (part[0].equals("set")) {
String[] clock = part[2].split(":");
times.put(part[1], new Time(Integer.parseInt(clock[0]) * 60 + Integer.parseInt(clock[1])));
} else if (part[0].equals("add")) {
times.put(part[1], times.get(part[1]).plus(Integer.parseInt(part[2])));
} else if (part[0].equals("diff")) {
out.add(String.valueOf(times.get(part[1]).until(times.get(part[2]))));
} else {
out.add(times.get(part[1]).text());
}
}
return out.toArray(new String[0]);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
java.util.List<String> all = new java.util.ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
all.add(line);
}
}
String[] lines = all.toArray(new String[0]);
System.out.println(String.join("\n", solve(lines)));
}
}
Hints (1)
- Why store minutes and not hours and minutes?