我正在努力压缩一些代码,现在我有4个方法,几乎完全相同的东西,除了for循环的建模有点不同。我将int up
,down
,right
和left
作为参数传递给此紧凑方法,这与我以前使用的4种方法一致。
通过为其中一个参数传递1而为其余参数传递0,我可以在单个循环中执行不同的操作,我只是在切换<或者>登录。
这是我正在尝试使用的代码行:
for (int i = (right*3)+(up*3); i <= (left*3)+(down*3); i= i + (left) + (down) - (up) - (right)) {
除了我需要将i <= (left...
部分切换到i >= (left...
right == 1
之外,所有内容都有效,是否有一种方法可以在Java中为for循环执行此操作?
如果这不可能,我可以制作2个不同的for循环,我只是不喜欢重复几乎相同的代码。
谢谢!
编辑:以下是4种方法:
public boolean moveRight() {
boolean didMove = false;
for (int a = 0; a <= 3; a++) {
for (int i = 3; i >= 0; i--) {
for (int j = 0; j < 4; j++) {
if (i != 3) {
if (valueArray[i + 1][j] == 0 && valueArray[i][j] != 0) {
valueArray[i + 1][j] = valueArray[i][j];
valueArray[i][j] = 0;
didMove = true;
button[i][j].setSize(80, 80);
} else if (valueArray[i + 1][j] == valueArray[i][j] && valueArray[i][j] != 0) {
valueArray[i + 1][j] = valueArray[i][j] * 2;
Score += valueArray[i][j] * 2;
valueArray[i][j] = 0;
didMove = true;
button[i][j].setSize(80, 80);
}
}
}
}
}
return didMove;
}
public boolean moveLeft() {
boolean didMove = false;
for (int a = 0; a <= 3; a++) {
for (int i = 0; i <= 3; i++) {
for (int j = 0; j < 4; j++) {
if (i != 0) {
if (valueArray[i - 1][j] == 0 && valueArray[i][j] != 0) {
valueArray[i - 1][j] = valueArray[i][j];
valueArray[i][j] = 0;
didMove = true;
button[i][j].setSize(80, 80);
} else if (valueArray[i - 1][j] == valueArray[i][j] && valueArray[i][j] != 0) {
valueArray[i - 1][j] = valueArray[i][j] * 2;
Score += valueArray[i][j] * 2;
valueArray[i][j] = 0;
didMove = true;
button[i][j].setSize(80, 80);
}
}
}
}
}
return didMove;
}
public boolean moveDown() {
boolean didMove = false;
for (int a = 0; a <= 3; a++) {
for (int i = 0; i < 4; i++) {
for (int j = 3; j >= 0; j--) {
if (j != 3) {
if (valueArray[i][j + 1] == 0 && valueArray[i][j] != 0) {
valueArray[i][j + 1] = valueArray[i][j];
valueArray[i][j] = 0;
didMove = true;
button[i][j].setSize(80, 80);
} else if (valueArray[i][j + 1] == valueArray[i][j] && valueArray[i][j] != 0) {
valueArray[i][j + 1] = valueArray[i][j] * 2;
Score += valueArray[i][j] * 2;
valueArray[i][j] = 0;
didMove = true;
button[i][j].setSize(80, 80);
}
}
}
}
}
return didMove;
}
public boolean moveUp() {
boolean didMove = false;
for (int a = 0; a <= 3; a++) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j <= 3; j++) {
if (j != 0) {
if (valueArray[i][j - 1] == 0 && valueArray[i][j] != 0) {
valueArray[i][j - 1] = valueArray[i][j];
valueArray[i][j] = 0;
didMove = true;
button[i][j].setSize(80, 80);
} else if (valueArray[i][j - 1] == valueArray[i][j] && valueArray[i][j] != 0) {
valueArray[i][j - 1] = valueArray[i][j] * 2;
Score += valueArray[i][j] * 2;
valueArray[i][j] = 0;
didMove = true;
button[i][j].setSize(80, 80);
}
}
}
}
}
return didMove;
}
答案 0 :(得分:1)
数学;将比较的两边乘以-1,将<=
变为>=
。
int sw = Math.abs(Math.signum(right - 1)) * 2 - 1; // -1 when right == 1 else 1
sw*i <= sw*((left*3)+(down*3))
这是否更优化或者更确切地说是色谱编程......