Too many 'if' statements?

前端 未结 26 1184
天涯浪人
天涯浪人 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:01

    I personally like to cascade ternary operators:

    int result = condition1
        ? result1
        : condition2
        ? result2
        : condition3
        ? result3
        : resultElse;
    

    But in your case, you can use:

    final int[] result = new int[/*16*/] {
        0, 0, 1, 2,
        0, 0, 2, 1,
        2, 1, 3, 3,
        1, 2, 3, 3
    };
    
    public int fightMath(int one, int two) {
        return result[one*4 + two];
    }
    

    Or, you can notice a pattern in bits:

    one   two   result
    
    section 1: higher bits are equals =>
    both result bits are equals to that higher bits
    
    00    00    00
    00    01    00
    01    00    00
    01    01    00
    10    10    11
    10    11    11
    11    10    11
    11    11    11
    
    section 2: higher bits are different =>
    lower result bit is inverse of lower bit of 'two'
    higher result bit is lower bit of 'two'
    
    00    10    01
    00    11    10
    01    10    10
    01    11    01
    10    00    10
    10    01    01
    11    00    01
    11    01    10
    

    So you can use magic:

    int fightMath(int one, int two) {
        int b1 = one & 2, b2 = two & 2;
        if (b1 == b2)
            return b1 | (b1 >> 1);
    
        b1 = two & 1;
    
        return (b1 << 1) | (~b1);
    }
    

提交回复
热议问题