问题
I'm drawing possible paths of a knight in chess and one case looks like this:
if (boundsOK(x + 1, y + 2)) {
temp = boardArray[x + 1][y + 2];
if (isLegalMove(x, y, x + 1, y + 2) != MoveType.NONE) {
moves.add(x);
moves.add(y);
moves.add(x + 1);
moves.add(y + 2);
move(x + 1, y + 2, x, y);
}
boardArray[x + 1][y + 2] = temp;
}
Now instead of 1 and 2, I want to construct a loop which would try out combinations:
1 2
-1 2
1 -2
-1 -2
2 1
-2 1
2 -1
-2 -1
But I don't know how to do it without unnecesary if's. Is there at least a smart way to do it?
回答1:
You can create a Vector class or similar (or use any Pair-like type), fill a list with your values and iterate over it (without paying much thought to performance):
var moves = List.of(
new Move(1,2),
new Move(-1,2),
new Move(1,-2),
new Move(-1,-2),
new Move(2,1),
new Move(-2,1),
new Move(2,-1),
new Move(-2,-1));
for (var move : moves) {
var x = move.getX();
var y = move.getY();
testMove(x, y) … // or refactor your method to receive a Move instance directly
}
If your are really trying to save some lines (are you code golfing?), you could create the instances with a loop, but that doesn't really make the code better (neither from a readability standpoint, nor from performance, nor from the number of characters to type):
var moves = new ArrayList<Move>();
for (int x : List.of(1,-1)) {
for (int y : List.of(2,-2)) {
moves.add(new Move(x,y));
}
}
for (int x : List.of(2,-2)) {
for (int y : List.of(1,-1)) {
moves.add(new Move(x,y));
}
}
Thinking a bit more, it can probably be condensed to 2 loops and 1 conditional, if we notice the fact that the moves always have to contain the numbers 1 and 2 and there are never moves (±1,±1) or (±2,±2):
var moves = new ArrayList<Move>(8);
var offsets = List.of(-2,-1,1,2);
for (int x : offsets) {
for (int y : offsets) {
if (Math.abs(x) != Math.abs(y)) {
moves.add(new Move(x,y));
}
}
}
But still, I think it is favorable to go the KISS (keep it simple, stupid) route and simply write out all possible moves. The intent is immediately clear and it is about the same number of lines (and you don't have to come up with clever ways to "compute" the moves).
来源:https://stackoverflow.com/questions/61548448/how-to-do-for-loop-with-all-possible-combinations-of-pairs-1-2