簡體   English   中英

如何將不同循環的結果相互比較?

[英]How do I compare results from different loops with each other?

我的問題是,使用我現在擁有的代碼,它不斷生成新的結果/骰子,但是說第 2 輪中的 result2 與第 3 輪中的 result1 相同,那么它也應該停止生成新結果。 現在不這樣做了。 我怎么能調整它呢?

int trials = 0;

for (int totalGames = 1; totalGames <= 3; totalGames++ ) {

    int result1, result2;

    // simulating dice rolls
    do {
        result1 = (int) (Math.random() * 6) + 1;
        result2 = (int) (Math.random() * 6) + 1;
        trials++;
        System.out.println(result1);
        System.out.println(result2);

    }
    while (result1 != result2);

您必須跟蹤某種集合中的每個結果,然后檢查結果是否已包含在該集合中:

/**
 * @return The amount of trials it took to get two matching numbers.
 */
public static int roleDice() {
    int trials = 0;
    HashSet<Integer> seenResults = new HashSet<Integer>();

    for (int totalGames = 1; totalGames <= 3; totalGames++) {
        int result1, result2;

        do {
            result1 = (int) (Math.random() * 6) + 1;
            result2 = (int) (Math.random() * 6) + 1;
            System.out.println(result1);
            System.out.println(result2);

            // Set.add(...) returns false if the value is already contained
            if (!(seenResults.add(result1) && seenResults.add(result2)))
                return trials;

            trials++;
        } while (result1 != result2);
    }

    return trials;
}

public static void main(String[] args) {
    int trials = roleDice();
}

通過這種方式,您可以在每次迭代中檢查先前的 result1 值是否與當前的 result2 值匹配,以及先前的 result2 值是否與當前的 result1 值匹配,直到條件評估為 true 並退出 while 循環。

int trials = 0;
for (int totalGames = 1; totalGames <= 3; totalGames++) {
    Set<Integer> result1Set = new HashSet<>();
    Set<Integer> result2Set = new HashSet<>();
    while (true) {
        trials++;
        int result1 = (int) (Math.random() * 6) + 1;
        int result2 = (int) (Math.random() * 6) + 1;
        if (result1Set.contains(result2) || result2Set.contains(result1)) {
            break;
        }
        result1Set.add(result1);
        result2Set.add(result2);
        System.out.println(result1);
        System.out.println(result2);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM