简体   繁体   中英

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

My problem is that with the code I have now, it keeps generating new results/dice, but say result2 in round 2 is the same as result1 in round3, then it should also stop the generating of new results. It doesn't do that now. How could I adjust st it does do that?

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);

You will have to keep track of each result in some sort of collection and then check if the result is already contained within that collection:

/**
 * @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();
}

This way you check if any of the previous result1 values match the current result2 value and if any of the previous result2 values match the current result1 value on every iteration until the condition evaluates to true and you break out of the while loop.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM