I have the following (simplified) conditions that need to be validated for a form I am writing:
a > b
a > c
a > d
b > c
b > d
c > d
Graphically, this can be seen as:

The user has freedom to enter values for a, b, c, and d, which is why they need to be validated to make sure they obey those rules. The problem I am having is writing something that clearly and efficiently evaluates each statement. Of course, the most obvious way would be to evaluate each statement separately as an if-statement. Unfortunately, this takes up a lot of lines of code, and I’d rather avoid cluttering up the method with a bunch of if-blocks that do almost the same thing. I did come up with the following nested for-loop solution, using arrays. I built an array of the values, and looped over it twice (demonstrated in Python-like pseudo-code):
A = [a, b, c, d]
for i in range(3):
for j in range(i, 4):
if i > j and A[i] >= A[j]:
print("A[i] must be less than A[j]")
else if i < j and A[i] <= A[j]:
print("A[j] must be greater than A[i]")
The problem I have with this solution is it is hard to read and understand – the solution just isn’t clear.
I have this nagging feeling that there is a better, clearer answer out there, but I can’t think of it for the life of me. This isn’t homework or anything – I am actually working on a project and this problem (or subtle variations of it) arose more than once, so I would like to make a reusable solution that is clear and efficient. Any input would be appreciated. Thanks!
1 Answer