There are too many if statements, can we reduce them?

Asked 1 years ago, Updated 1 years ago, 124 views

The code below works the way I want it to. The cord is so dirty. I tried to shorten it several times, but it doesn't make much difference. Is there any mathematical formula that can help reduce code? Or is it enough to get 16 if questions?

To explain the code, it's a turn-based game. Two players each have four action buttons, and the values are 0 to 3. If the result value is 0, no one can win. If it's 1, 1P wins. If it's 2, 2P wins. If it's 3, both of them win.

public int fightMath(int one, int two) {

    if(one == 0 && two == 0) { result = 0; }
    else if(one == 0 && two == 1) { result = 0; }
    else if(one == 0 && two == 2) { result = 1; }
    else if(one == 0 && two == 3) { result = 2; }
    else if(one == 1 && two == 0) { result = 0; }
    else if(one == 1 && two == 1) { result = 0; }
    else if(one == 1 && two == 2) { result = 2; }
    else if(one == 1 && two == 3) { result = 1; }
    else if(one == 2 && two == 0) { result = 2; }
    else if(one == 2 && two == 1) { result = 1; }
    else if(one == 2 && two == 2) { result = 3; }
    else if(one == 2 && two == 3) { result = 3; }
    else if(one == 3 && two == 0) { result = 1; }
    else if(one == 3 && two == 1) { result = 2; }
    else if(one == 3 && two == 2) { result = 3; }
    else if(one == 3 && two == 3) { result = 3; }

    return result;
}

java math formula if문

2022-09-22 22:30

1 Answers

I don't know about the formula, but I can make a table like this and put the results in.

final int[][] result = new int[][] {
  { 0, 0, 1, 2 },
  { 0, 0, 2, 1 },
  { 2, 1, 3, 3 },
  { 1, 2, 3, 3 }
};
return result[one][two];


2022-09-22 22:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.