Rolling two dices. Count number of iterations for both of them to match condition

StackOverflow https://stackoverflow.com/questions/21526370

  •  06-10-2022
  •  | 
  •  

Pregunta

In my program I have two dices with 100 faces. I make it count the amount of rolls it takes for dice one (d1) to equal 99 AND dice two (d2) to equal 26.

package diceroll;

import java.util.Random;

public class DiceRoll {

public static void main(String[] args) {

    int count = 0;
    int d1 = 0;
    int d2 = 0;

    while (d1 != 99 && d2 != 29) {
        d1 = (int) (Math.random() * 100) + 1;
        d2 = (int) (Math.random() * 100) + 1;
        count += 1;
    }
    System.out.println(count + " " + d1 + " " + d2);
}

When using the AND operator (&&) the while loop only works until one of the numbers is found, however when using the OR operator (d1 != 99 || d2 != 29) the while loop works until both of them are matched.

Can somebody explain why OR gives the expected results, whilst AND doesn't?

¿Fue útil?

Solución

The loop

while (condition)

keeps looping until condition is false. Your loop is:

while (d1 != 99 && d2 != 29) {

but both halves of the test must be true for the whole condition to be true. Once one of the numbers matches, one half will be false (it will not be not equal).

If you change the condition to OR:

while (d1 != 99 || d2 != 29) {

then only one side needs to be true for the whole condition to be true, or put another way, both sides need to be false for the whole condition to be false. This OR condition can be expressed in English as "while either of the numbers is not the target". Only when both numbers are their target is the entire condition false.

Otros consejos

That's how AND works. It just looks for a single expression to return false to terminate the loop. It doesn't bother whether d1 is 69 or not, if d2 becomes 29 and vice versa.

But when you use OR, it checks for both the conditions. That way, even if d2 becomes 29 and d1 is still not 69 it continues to loop till d1 becomes 69, and thus evaluating to false only when both the conditions are satisfied.

When you're using &&, if one of the dice doesn't equal the desired number, your conditional still returns false. For example, if d1=99 and d2=1, your while conditional would read: 99 != 99 && 1 != 29 -> false && true -> false. So it exits.

Yeah, I understand it now. By using while not and OR logic, I created NOR logic which has the following table:

A B Z

0 0 1

0 1 0

1 0 0

1 1 0

Thanks for the help guys! :)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top