Finding valid neighbors in 2D array

前端 未结 7 686
情书的邮戳
情书的邮戳 2021-01-22 07:13

So, I have a 4x4 2D array (it will always be these dimensions). Starting with a location on the array, some row and column, I want to find all of its valid neighbors. So far, I

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-22 07:54

    The way I would do it would be to have a seperate method.

    public void example(int changeSign, boolean shouldCheckRow,boolean shouldCheckColumn){
        int num = 4;
        if(changeSign < 0)
            num = 0;
        if(shouldCheckRow)
            //adding a negative is the same as subtracting so if you add -1, you're really subtracting by one.
    
            if(!((row + changeSign) < num))
                //do stuff
        else
            if(!((col + changeSign) < num))
                //do stuff
    }
    

    And the method calls would be

    public static void main(String args[]){
        int shouldTestRight = 1;
        int shouldTestLeft = -1;
        int shouldTestUp = 1;
        int shouldTestDown = -1;
        // so if you want to test up or right, the first parameter should be positive
        // if you want to test for down or left, the first parameter should be negative
        // this is because the negative will flip the sign.
        // if you should change the row, the second parameter should be true
        // if you should change the column, the third parameter should be true.
        example(shouldTestRight,true,false);
        example(shouldTestLeft,true,false);
        example(shouldTestUp,false,true);
        example(shouldTestDown,false,true);
    }
    

    Of course, you don't have to include the extra ints in the method you're calling from but I did it for extra code readability.

提交回复
热议问题