Assertion Message: First Difference
Problem
A test compares an expected list of numbers with the actual list and must explain a failure well. The first line is the expected list, the second line is the actual list (numbers separated by spaces). Print equal if they are the same. If the lengths differ, print length differs: expected E but was A. Otherwise, print difference at index I: expected X but was Y for the first index where they differ.
Constraints
- 1 <= length <= 100
Examples
Input
1 2 3 1 5 3
Output
difference at index 1: expected 2 but was 5
Solutions
A good assertion tells where and how the values differ. Checking the length first gives a clear message for lists of different sizes. The loop then reports the first index that differs, with both values.
/*
* Problem : Explain the failure.
* Input : Two lists.
* Output : One message.
* Approach: Loop with index
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: An assertion helper that returns a message that tells exactly what is wrong. The loop stops at the first difference.
static String compare(int[] expected, int[] actual) {
if (expected.length != actual.length) {
return "length differs: expected " + expected.length + " but was " + actual.length;
}
for (int i = 0; i < expected.length; i++) {
if (expected[i] != actual[i]) {
return "difference at index " + i + ": expected " + expected[i] + " but was " + actual[i];
}
}
return "equal";
}
static int[] parse(String line) {
String[] part = line.split(" ");
int[] values = new int[part.length];
for (int i = 0; i < part.length; i++) {
values[i] = Integer.parseInt(part[i]);
}
return values;
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
// Step 2: The test reads both lists and prints the message.
return new String[] {compare(parse(lines[0]), parse(lines[1]))};
}
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 (2)
- Why check the length first?
- Why report the index?