Too many 'if' statements?

前端 未结 26 1146
天涯浪人
天涯浪人 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 16:43

    This uses a little bit of bitmagic (you're already doing it by holding two bits of information (low/high & attack/block) in a single integer):

    I haven't run it, only typed it here, please doublecheck. The idea surely works. EDIT: It is now tested for every input, works fine.

    public int fightMath(int one, int two) {
        if(one<2 && two<2){ //both players blocking
            return 0; // nobody hits
        }else if(one>1 && two>1){ //both players attacking
            return 3; // both hit
        }else{ // some of them attack, other one blocks
            int different_height = (one ^ two) & 1; // is 0 if they are both going for the same height - i.e. blocker wins, and 1 if height is different, thus attacker wins
            int attacker = one>1?1:0; // is 1 if one is the attacker, two is the blocker, and 0 if one is the blocker, two is the attacker
            return (attacker ^ different_height) + 1;
        }
    }
    

    Or should I suggest to separate the two bits of information into separate variables? Code based mostly on bit operations like this above is usually really hard to maintain.

提交回复
热议问题