Too many 'if' statements?

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

    Why not use an array?

    I will start from the beginning. I see a pattern, the values goes from 0 to 3 and you want catch all possible values. This is your table:

    0 & 0 = 0
    0 & 1 = 0
    0 & 2 = 1
    0 & 3 = 2
    1 & 0 = 0
    1 & 1 = 0
    1 & 2 = 2
    1 & 3 = 1
    2 & 0 = 2
    2 & 1 = 1
    2 & 2 = 3
    2 & 3 = 3
    3 & 0 = 2
    3 & 1 = 1
    3 & 2 = 3
    3 & 3 = 3
    

    when we look at this same table binary we see the following results:

    00 & 00 = 00
    00 & 01 = 00
    00 & 10 = 01
    00 & 11 = 10
    01 & 00 = 00
    01 & 01 = 00
    01 & 10 = 10
    01 & 11 = 01
    10 & 00 = 10
    10 & 01 = 01
    10 & 10 = 11
    10 & 11 = 11
    11 & 00 = 10
    11 & 01 = 01
    11 & 10 = 11
    11 & 11 = 11
    

    Now maybe you already see some pattern but when I combine value one and two I see that you're using all values 0000, 0001, 0010,..... 1110 and 1111. Now let's combine value one and two to make a single 4 bit integer.

    0000 = 00
    0001 = 00
    0010 = 01
    0011 = 10
    0100 = 00
    0101 = 00
    0110 = 10
    0111 = 01
    1000 = 10
    1001 = 01
    1010 = 11
    1011 = 11
    1100 = 10
    1101 = 01
    1110 = 11
    1111 = 11
    

    When we translate this back into decimal values we see an very possible array of values where the one and two combined could be used as index:

    0 = 0
    1 = 0
    2 = 1
    3 = 2
    4 = 0
    5 = 0
    6 = 2
    7 = 1
    8 = 2
    9 = 1
    10 = 3
    11 = 3
    12 = 2
    13 = 1
    14 = 3
    15 = 3
    

    The array is then {0, 0, 1, 2, 0, 0, 2, 1, 2, 1, 3, 3, 2, 1, 3, 3}, where it's index is simply one and two combined.

    I'm not a Java programmer but you can get rid of all if statements and just write it down as something like this:

    int[] myIntArray = {0, 0, 1, 2, 0, 0, 2, 1, 2, 1, 3, 3, 2, 1, 3, 3};
    result = myIntArray[one * 4 + two]; 
    

    I don't know if a bitshift by 2 is faster than multiplication. But it could be worth a try.

提交回复
热议问题