我有一个方法可以通过数组从点 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/