2
\$\begingroup\$

Is there any way I can minimise this code.The code will get the neighbours of the current node and point the arrow to the current node

private boolean isDiagonal(int x, int y, Node node) {
    if (x == -1 && y == 1) {
        node.arrow.setDrawable("bottom-right");
        return true;
    } else if (x == 1 && y == 1) {
          node.arrow.setDrawable("bottom-left");
        return true;
    } else if (x == -1 && y == -1) {
          node.arrow.setDrawable("top-right");
        return true;
    } else if (y == -1 && x == 1) {
         node.arrow.setDrawable("top-left");
        return true;
    } 
    // Determine here if it's cross
    else if (x == -1 && y == 0) {
        node.arrow.setDrawable("right");
        return true;
    } else if (x == 1 && y == 0) {
        node.arrow.setDrawable("left");
        return true;
    } else if (x == 0 && y == -1) {
        node.arrow.setDrawable("up");
        return true;
    } else if (y == 1 && x == 0) {
        node.arrow.setDrawable("down");
        return true;
    }
    return false;
}

output

enter image description here

\$\endgroup\$
1
\$\begingroup\$

Just as I answered yesterday in BFS in a grid with wall breaking saldo in Java : define a direction and use it:

enum Direction {
    // define directions for each pair of offsets
    NORTH(-1, 0, "up"),
    NORTHEAST(-1, 1, "top-right"),
    SOUTH(1, 0, "...."),
    ...
    ;

    public final int offsetX;
    public final int offsetY;
    public final String drawableValue;

    private Direction(int offsetX, int offsetY, String drawableValue) {
        this.offsetX = offsetX;
        this.offsetY = offsetY;
        this.drawableValue = drawableValue;
    }
};

private boolean isDiagonal(int x, int y, Node node) {
    for(Direction dir : Direction.values())
        if(x == dir.offsetX && y == dir.offsetY) {
           node.arrow.setDrawable(dir.drawableValue);
           return true;
        }
    return false;
}

Apart from that, the method-name is a lie: it does NOT check for diagonals only, so you should find a name which describes the actual action.

(And just because this is code-review and someone will be tempted to say: add braces to the for loop: no. This is the style I prefer, I know that other people like it in other ways. ;-))

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.