减少类似方法的数量

时间:2017-06-12 23:51:18

标签: java algorithm performance

我有一个方法可以通过数组从点a到点b(它通过递增迭代)或从b到a(它通过递减迭代)执行某些操作。

这两种方法必须是a到b和b到a,因为我一开始不知道,我将在哪里结束。在我的实现中,它们只有一行不同。

在更多方面,我仍然只是在直线上。问题从两个(左,右)扩展到八个(向上,向右,向右,向右等),32等功能。他们也开始变化多行。

解决问题的最佳方法是什么?

我必须在java中处理它。

2个维度的示例(八个函数中的三个,以涵盖所有可能性):

void doSomethingToCellsRIGHT(int x, int y) {
    while(condition) {
        board[x][y].changeSomething();
        x++;
    }
}

void doSomethingToCellsLEFT(int x, int y) {
    while(condition) {
        board[x][y].changeSomething();
        x--;
    }
}
void doSomethingToCellsUP_LEFT(int x, int y) {
    while(condition) {
        board[x][y].changeSomething();
        y++;
        x--;
    }
}

3 个答案:

答案 0 :(得分:2)

添加枚举

public enum DIRECTION {
    Right,
    Left,
    Up,
    Down
}

您可以执行此操作并拥有多个可选参数,您始终需要至少一个方向;

void doSomethingToCells(int x, int y, DIRECTION... directions){
    while(condition){
        board[x][y].changeSomething();

        for(DIRECTION dir:directions){  
            y+= dir == DIRECTION.Up ? 1 : 0;
            y-= dir == DIRECTION.Down ? 1 : 0;
            x+= dir == DIRECTION.Right ? 1 : 0;
            x-= dir == DIRECTION.Left ? 1 : 0;
        }
   }
}

你可以致电

doSomethingWithCells( 1,1, Up, Left) . // This would go x-- and y++
doSomethingWithCells( 1,1, Up)         // This would go y++

你甚至可以打电话

doSomethingWithCells( 1,1, Left, Left) .  //This would skip every second cell to the left

答案 1 :(得分:1)

很酷,一个很好的问题,代码与@Derek完全相同,但是更多OO:

定义Move接口

public interface Move {
    public void move(int x, int y);
}

enum with method body

中实现它
public enum Movement implements Move {
    RIGHT() {
        public void move(int x, int y) {
            x++;
        }
    },

    LEFT() {
        public void move(int x, int y) {
            x--;
        }
    },

    UP() {
        public void move(int x, int y) {
            y++;
        }
    },

    DOWN() {
        public void move(int x, int y) {
            y--;
        }
    };
}

如何使用:

public void doSomething(int x, int y, Movement... movements) {
    while (condition) {
        board[x][y].changeSomething();

        for (Movement movement : movements) {
            movement.move(x, y);
        }
    }
}

呼叫

doSomething(1, 2, Movement.DOWN, Movement.RIGHT);

答案 2 :(得分:1)

除了方法

之外,黎平的答案可能会有所改善
    public void move(int x, int y) {
        x++;
    }

什么都不做(在这里增加局部变量是一个无操作)。

无论如何,我会以更短且可能更快的方式做到这一点:

public interface Move {
    public int dx();
    public int dy();
}

@RequiredArgsConstructor 
public enum Movement implements Move {
    RIGHT(+1, 0),
    LEFT(-1, 0),
    UP(0, +1),
    DOWN(0, -1);

    private final dx;
    private final dy;
}

The Lombok annotation完全符合名称所说的内容。

用法应该是显而易见的。