Comparison of 5 integers in least number of comparisons
I have this code and need to make sure all the resulting variables are equal?
long result1 = timer.CalculateElapsedTimeInMinutes();
long result2 = timer.CalculateElapsedTimeInMinutes();
long result3 = timer.CalculateElapsedTimeInMinutes();
long result4 = timer.CalculateElapsedTimeInMinutes();
long result5 = timer.CalculateElapsedTimeInMinutes();
This is what I did, but I feel like it can be done in an easier way, maybe not?
bool allEqual = (result1 == result2) && (result3 == result4) && (result1 == result3) && (result1 == result5);
Thank.
source to share
It's just possible that there is some hacky / clever way that can be done with XOR or something, but your code makes it clear what you want to do and will still be ridiculously fast. The chances of this becoming a bottleneck are close enough to 0 not to be considered IMO - so go with the most readable code.
I would be more consistent in your comparisons:
bool allEqual = (result1 == result2) &&
(result1 == result3) &&
(result1 == result4) &&
(result1 == result5);
It's easier to see visually that you have good reason, IMO.
source to share
You can also do this with reference using the All extension method.
var results = new long[] {
timer.CalculateElapsedTimeInMinutes(),
timer.CalculateElapsedTimeInMinutes(),
timer.CalculateElapsedTimeInMinutes(),
timer.CalculateElapsedTimeInMinutes(),
timer.CalculateElapsedTimeInMinutes()
};
bool allEqual = results.All(x => x == results[0]);
source to share
It depends on what you mean by comparison. You can do this using just one explicit comparison operator:
bool result =
((result1 ^ reesult2) | (result1 ^ result3) | (result1 ^ result4) | (result1 ^ result5))==0;
It may even take advantage of the generated code - code that uses boolean and should stop performing comparisons as soon as it finds any non-equal value. This means that each comparison must be done individually and it must include code to complete testing after each comparison.
Unless you're doing this inside a really complex loop, however, it's not worth what you think is most readable.
source to share
You can also make a helper function for this:
bool AllEqual<T>(params T[] values) where T : IEquatable<T> {
// make a decision here and document it
if (values.Length < 1) return true; // I guess?
bool result = true;
T first = values[0];
for (int i = 1; i < values.Length; i++) {
result = result && first.Equals(values[i]);
}
return result;
}
source to share