Created
May 4, 2015 23:54
-
-
Save fnk0/76d8bd0f6e527806c322 to your computer and use it in GitHub Desktop.
Simple methots to calculate the Min or Max of a list of integers. The same logic can be applied for floats, double, longs, etc..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Calculates the max of several integers at once. | |
| * | |
| * @param values | |
| * 2 or more integers to which the maximum should be calculated | |
| * @return The maximum value in the list | |
| */ | |
| public static int max(@NonNull int... values) { | |
| if (values.length < 2) { | |
| throw new RuntimeException("At least 2 integers are needed in order to calculate the maximum value."); | |
| } | |
| int max = values[0]; | |
| for (int i = 1; i < values.length; i++) { | |
| max = Math.max(max, values[i]); | |
| } | |
| return max; | |
| } | |
| /** | |
| * Calculates the min of several integers at once. | |
| * | |
| * @param values | |
| * 2 or more integers to which the minimum should be calculated | |
| * @return The minimum value in the list | |
| */ | |
| public static int min(@NonNull int... values) { | |
| if (values.length < 2) { | |
| throw new RuntimeException("At least 2 integers are needed in order to calculate the minimum value"); | |
| } | |
| int min = values[0]; | |
| for (int i = 1; i < values.length; i++) { | |
| min = Math.min(min, values[i]); | |
| } | |
| return min; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment