如何在Java中删除重复的列表遍历

sie*_*ema 1 java oop arraylist

我正在创建一个solitare纸牌游戏,在arraylist中存储卡片.我想创建两种方法来检查玩家的移动和游戏.

一个布尔函数,它通过ArrayList并检查是否有任何可能的移动.如果有可能,该方法返回true.

第二个动作.它还会通过ArrayList并检查是否有任何可能的移动,进行此移动并停止工作.为了阻止它我使用return true.但我认为这不是好方法.

两个函数非常相似,代码重复.怎么解决?看起来这个方法是否可以返回布尔值或两个可以移动的卡(a和b)?

public boolean makeMove() {
    int a = 0; //index of one card
    int b; //index of second card
    for (b = getSize() - 1; b > 0; b--) {
        for (a = 0; a < b; a++) {
            if (isCorrectMove(a, b)) {
                swap(a, b); //makes move
                return true; //exit after move
            }
        }
    }
    return false; //if there was no move
}

public boolean isPossibleAnyMove() {int a = 0; //index of one card
        int b; //index of second card
        for (b = getSize() - 1; b > 0; b--) {
            for (a = 0; a < b; a++) {
                if (isCorrectMove(a, b)) {
                    return true; //returns true if there was a move
                }
            }
        }
        return false; //if there was no move
    }
Run Code Online (Sandbox Code Playgroud)

fab*_*ian 6

你可以创建一个函数来找到第一个正确的移动; 此函数将返回包含值ab正确移动的对象,或者null如果没有正确的移动.

private static class Move {

    int a, b;

    Move(int a, int b) {
        this.a = a;
        this.b = b;
    }

}

private Move findFirstCorrectMove() {
    int a = 0; //index of one card
    int b; //index of second card
    for (b = getSize() - 1; b > 0; b--) {
        for (a = 0; a < b; a++) {
            if (isCorrectMove(a, b)) {
                return new Move(a,b);
            }
        }
    }
    return null; //if there was no move
}

public boolean makeMove() {
    Move move = findFirstCorrectMove();
    if (move != null) {
        swap(move.a, move.b);
        return true;
    }
    return false;
}

public boolean isPossibleAnyMove() {
    return findFirstCorrectMove() != null;
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以简单地使用int[]数组而不是创建新Move类.


您还可以使用策略模式来处理移动.我希望代码中的一些java 8功能不会打扰你:

@FunctionalInterface
interface MoveConsumer {
    void acceptMove(int a, int b);
}

private boolean findFirstCorrectMove(MoveConsumer moveConsumer) {
    int a = 0; //index of one card
    int b; //index of second card
    for (b = getSize() - 1; b > 0; b--) {
        for (a = 0; a < b; a++) {
            if (isCorrectMove(a, b)) {
                moveConsumer.acceptMove(a, b);
                return true;
            }
        }
    }
    return false; //if there was no move
}

public boolean makeMove() {
    return findFirstCorrectMove(this::swap); // assuming here that swap is non-static
}

public boolean isPossibleAnyMove() {
    return findFirstCorrectMove((a, b) -> {});
}
Run Code Online (Sandbox Code Playgroud)