Validated Range (record)
Problem
Every line has two whole numbers low and high. A range is only valid if low <= high. Print length N (the count of whole numbers from low to high, both included) for a valid range, or invalid range if low is bigger than high. The object must refuse to exist when it is invalid.
Constraints
- 1 <= lines <= 10^4
- |number| <= 10^9
Examples
Input
1 5 6 5
Output
length 5 invalid range
Solutions
A normal class works in every Java version. The check in the constructor makes sure that no invalid Range can exist.
/*
* Problem : Process lines.
* Input : Several lines.
* Output : One result per line.
* Approach: A normal class.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: A normal class needs fields, a constructor, a check and a getter. That is a lot of code for a simple value.
static final class Range {
private final long low;
private final long high;
Range(long low, long high) {
if (low > high) {
throw new IllegalArgumentException("invalid range");
}
this.low = low;
this.high = high;
}
long length() {
return high - low + 1;
}
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
String[] output = new String[lines.length];
for (int i = 0; i < lines.length; i++) {
String[] part = lines[i].split(" ");
// Step 2: The constructor throws for a bad range. We catch the error and print a message.
try {
output[i] = "length " + new Range(Long.parseLong(part[0]), Long.parseLong(part[1])).length();
} catch (IllegalArgumentException error) {
output[i] = error.getMessage();
}
}
return output;
}
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 check in the constructor and not later?