Boundary Value Test Inputs
Problem
A rule accepts the whole numbers from low to high (both included). Good tests check values around the limits. Read low and high and print the test values low-1, low, low+1, high-1, high and high+1 in ascending order. Print each different value only once.
Constraints
- -10^9 <= low <= high <= 10^9
Examples
Input
1 10
Output
0 1 2 9 10 11
Input
5 6
Output
4 5 6 7
Solutions
Most bugs sit at the limits: < instead of <=, or a loop that stops one step too early. Testing just below, on, and just above each limit finds them. For a range with one value, the six values collapse to three.
/*
* Problem : Boundary values.
* Input : Two integers low and high.
* Output : The test values.
* Approach: A set of limits.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(long a, long b) {
// Step 1: A TreeSet removes repeated values and keeps the values sorted.
java.util.TreeSet<Long> values = new java.util.TreeSet<>();
// Step 2: Just outside, on, and just inside each limit: the places where off-by-one mistakes hide.
values.add(a - 1);
values.add(a);
values.add(a + 1);
values.add(b - 1);
values.add(b);
values.add(b + 1);
// Step 3: Copy the values to an array. The shared output code prints int values, which is enough for our range.
int[] result = new int[values.size()];
int index = 0;
for (long value : values) {
result[index++] = (int) value;
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextLong();
long b = scanner.nextLong();
System.out.println(Arrays.stream(solve(a, b)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- Why do bugs often hide at the limits?