I have a general question - regarding testing of values, I have run into this issue multiple time and I end up with some unsightly long code to accomplish something that logically seems simple.
the issue - I have one or multiple values I want to test against other values....SUCH THAT my code ends up looking like this (conceptually)
IF (A > B
AND A < C
AND A < D
AND A < E)
THEN print "Yes"
LOGICALLY I can express this as IF A > b,c,d,e etc.
If I also need to check other values in that list - you can see that the conditional statement to test against could become significantly larger and messier than the code the condition is intended to yield...
there MUST be a way problematically OR mathematically to express this common instance.
I know each language has 'syntax' specific ways to to this but .. I'll take suggestions and try em.
You have two questions here: 1) is there a cleaner way to write this code? and 2) is this computationally efficient?
murgatroid99 and τεκ both have good answers to how to produce cleaner code. But both of these methods are actually (at least on the face of things, assuming the compiler doesn't optimize under the hood) less computationally efficient.
Think about it: the statement if a > max(b,c,d,e)
tells the system to call max() -- which adds to the stack, copies arguments, etc. The call will probably get inlined one way or another, so you're not talking about a huge loss in performance, but there is some overhead. And the max() function will have to compare each of the numbers with each other number, taking O(n) time to complete.
On the other hand, the statement you've originally written, IF (A > B AND A < C AND A < D AND A < E)
will short-circuit out the first time it comes across a comparison that does not evaluate to true. So what you really want, if you clean up this code, is a function that does the same. Something like
boolean smallerThanElements(int a, int[] elements) {
for (int elt : elements) {
if (a > elt) return false;
}
return true;
}
Now your list can grow to arbitrary size, but will still short-circuit out. You still have some overhead from the function call, but you've cut your expected performance to O(n/2) (the average of the best case O(1) and the worst case O(n)). And it simplifies your if statement down to if (a > b AND smallerThanElements(a, eltArray))
.