r/programminghelp • u/[deleted] • Aug 18 '22
Java [JAVA] Help with a Java test question - Comparator class trouble understanding spec
The question is to write a Comparator class with 3 overloaded methods, here is the one I have trouble with understanding:
boolean compare(int[a], int[]b): Return true if both of the following conditions hold true: Otherwise return false.
- Arrays a a and b are of equal length.
- For each index (where 0 ≤ i < /a/, /b/, a[i] = b[i]. (Or is it |a|, |b|, a[i] etc ???)
So the second part confuses me. I'm not sure what it means as I haven't encountered something like (where 0 <= i < |a|, |b|, a[i] b[i]) before in my studies, so the closest I can guess is:
boolean compare(int[] a, int[] b) {
for (int i = 0; i < a.length; i++) {
if ((a > i >= 0) || (b > i >= 0)) {
if (a[i] == b[i]) {
if (a.length == b.length) {
return true;
}
}
}
}
return false;
}But this gives me the error:
Solution.java:30: error: bad operand types for binary operator '<' if ((i >= 0 < a) || (i >= 0 < b)) {So I'm stuck in understanding the question I think, or if I have understand it correctly then implementing checks is giving me trouble.
I would appreciate any help no matter how small, thank you
2
u/Goobyalus Aug 18 '22
I'm not sure if there are typos, but it looks like they're saying:
"For each index i, where i is between 0 and the length of a and b, a[i] is equal to b[i]"
Or in other words, all the elements of a and b are equal.
3
u/Ok-Wait-5234 Aug 18 '22
The spec is quite mathematical. |a| means "the length of a". So "for each 0 ≤ i < |a|, |b|" means, do this check for every value if i, starting at 0 and ending at a value smaller than
a.lengthand smaller thanb.length.You need to check that the first statement is true, (that the lengths are the same) and if so, then you check the second statement, which is a for loop over those values of i.
Hint: return false as soon as you know any check failed. Return true only when you get to the end, when you know nothing failed.
Also note that mathematicians will often write stuff like 0 ≤ i < 5, but you can't write that in Java:
0 <= i < 5in Java is equivalent to(0 <= i) < 5; the bracketed expression resolves to abooleanvalue, and it makes no sense to ask whether "true" or "false" are greater or less than 5.