Too many 'if' statements?

前端 未结 26 1068
天涯浪人
天涯浪人 2020-11-30 16:24

The following code does work how I need it to, but it\'s ugly, excessive or a number of other things. I\'ve looked at formulas and attempted to write a few solutions, but I

相关标签:
26条回答
  • 2020-11-30 17:06

    You can create matrix which contains results

    int[][] results = {{0, 0, 1, 2}, {0, 0, 2, 1},{2, 1, 3, 3},{2, 1, 3, 3}};
    

    When you want to get value you will use

    public int fightMath(int one, int two) {
      return this.results[one][two]; 
    }
    
    0 讨论(0)
  • 2020-11-30 17:06

    A good point would be to define the rules as text, you can easier derive the correct formula then. This is extracted from laalto's nice array representation:

    { 0, 0, 1, 2 },
    { 0, 0, 2, 1 },
    { 2, 1, 3, 3 },
    { 1, 2, 3, 3 }
    

    And here we go with some general comments, but you should describe them in rule terms:

    if(one<2) // left half
    {
        if(two<2) // upper left half
        {
            result = 0; //neither hits
        }
        else // lower left half
        {
            result = 1+(one+two)%2; //p2 hits if sum is even
        }
    }
    else // right half
    {
        if(two<2) // upper right half
        {
            result = 1+(one+two+1)%2; //p1 hits if sum is even
        }
        else // lower right half
        {
            return 3; //both hit
        }
    }
    

    You could of course crunch this down to less code, but it is generally a good idea to understand what you code rather than finding a compact solution.

    if((one<2)&&(two<2)) result = 0; //top left
    else if((one>1)&&(two>1)) result = 3; //bottom right
    else result = 1+(one+two+((one>1)?1:0))%2; //no idea what that means
    

    Some explanation on the complicated p1/p2 hits would be great, looks interesting!

    0 讨论(0)
提交回复
热议问题