I have 16 methods in Java that return int
values. I need to find the one that returns the highest value.
I initially implemented this:
private int best() {
int max = playGame(ONES);
max = Math.max(max, playGame(TWOS));
max = Math.max(max, playGame(THREES));
max = Math.max(max, playGame(FOURS));
max = Math.max(max, playGame(FIVES));
max = Math.max(max, playGame(SIXES));
max = Math.max(max, playGame(SEVENS));
max = Math.max(max, playGame(EIGHTS));
max = Math.max(max, playGame(THREE_OF_A_KIND));
max = Math.max(max, playGame(FOUR_OF_A_KIND));
max = Math.max(max, playGame(FULL_HOUSE));
max = Math.max(max, playGame(SMALL_STRAIGHT));
max = Math.max(max, playGame(LARGE_STRAIGHT));
max = Math.max(max, playGame(ALL_DIFFERENT));
max = Math.max(max, playGame(CHANCE));
max = Math.max(max, playGame(ALL_SAME));
return max;
}
To make this slightly better, I could reduce one comparison by comparing two methods simultaneously.
private int best() {
int max1 = Math.max(playGame(ONES), playGame(TWOS));
int max2 = Math.max(playGame(THREES), playGame(FOURS));
int max3 = Math.max(playGame(FIVES), playGame(SIXES));
int max4 = Math.max(playGame(SEVENS), playGame(EIGHTS));
int max5 = Math.max(playGame(THREE_OF_A_KIND), playGame(FOUR_OF_A_KIND));
int max6 = Math.max(playGame(FULL_HOUSE), playGame(SMALL_STRAIGHT));
int max7 = Math.max(playGame(LARGE_STRAIGHT), playGame(ALL_DIFFERENT));
int max8 = Math.max(playGame(CHANCE), playGame(ALL_SAME));
int max11 = Math.max(max1, max2);
int max12 = Math.max(max3, max4);
int max13 = Math.max(max5, max6);
int max14 = Math.max(max7, max8);
int max21 = Math.max(max11, max12);
int max22 = Math.max(max13, max14);
int max = Math.max(max21, max22);
return max;
}
I mentioned 16 methods as playGame(CONSTANT)
callbacks different methods based on the constant.
However, this code is still bad. What could be a better way to achieve this?
enum
? \$\endgroup\$public static final
values in a separate file. \$\endgroup\$playGame()
do? \$\endgroup\$