java - 减少相似方法的数量

标签 java algorithm performance

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

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

在更多维度上我仍然只做直线。问题从2个(左、右)扩展到8个(上、右上、右、右下等),32个等等函数。他们也开始在更多行中发生变化。

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

我必须在java中处理它。

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

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--;
    }
}

最佳答案

添加一个枚举

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

关于java - 减少相似方法的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510333/

相关文章:

c - 与单进程场景​​相比,多进程场景中的访问时间意外减少

java - 运行 dockerizing 镜像时找不到主类

java - C 与 Java 的编译模型有何不同?

objective-c - 我怎样才能在 Objective-C 中加速这个强力加法算法?

网格切片/轮廓的算法和库?

keyboard - 学习触摸打字的最佳方法是什么? [复制]

java - 反编译JavaEE

java - 使用机器货币不是美元的 Apache POI 将 Excel 单元格格式化为美元

python - 无偏返回 n 个随机正数 (>=0) 的列表,使得它们的总和 == 总和

java - Hibernate saveOrUpdate 大数据