I have quite a tricky question where I currently cannot find an answer to:
What I have is an enum with x variants like:
public enum Symbol {
ROCK,
PAPER,
SCISSORS;
}
This enum is supposed to be extended by one, two, ... variants (like Rock, Paper, Scissors, Spock, Lizard) and I am searching for an option to store the result of the combinations (in the example, who is winning). Like in Rock, Paper, Scissors I cannot assign a weight/value to the enum which then could be used for comparision. The result of the comparision is not based on logic. What I am currently doing is:
public Result calculateResult(Symbol hand2) {
Symbol handP1 = this;
Symbol handP2 = hand2;
if (handP1 == Symbol.ROCK) {
switch (handP2) {
case SCISSORS:
return Result.WIN;
case ROCK:
return Result.TIE;
case PAPER:
return Result.LOOSE;
} ....
I do this for every possible option for the first element of the comparison (in the example hand1). With 3 enums this is quite easy and tidy, but with 4,5 or more it gets messy real quick. Using if and else if for comparison is not really suitable as well.Is there any better way to handle this issue?
I have setup a repl if you want to try it out yourself: REPL Link
Using for or more choices break the circular relationship you might have with 3 choices. Please see here for an example:
Thanks for any tips and hints which might help me get a better solution