When simulating the spin of a three-wheel slot machine, how do we detect three of a kind?
The following condition recognizes three of a kind:
var s1 = 'lemon', s2 = 'lemon', s3 = 'lemon';
alert((s1 == s2) && (s1 == s3) && (s2 == s3));
We can modify it to control a loop that spins the wheels:
s1 = RandomOneOf(['lemon', 'cherry', 'bar', 'donut']);
s2 = RandomOneOf(['lemon', 'cherry', 'bar', 'donut']);
s3 = RandomOneOf(['lemon', 'cherry', 'bar', 'donut']);
while(!((s1 == s2) && (s1 == s3) && (s2 == s3))){
//spin again...
}
Applying
Demorgan's Law we get:
while(!(s1 == s2) || !(s1 == s3) || !(s2 == s3)){
//spin again...
}
Equivalently:
while((s1 != s2) || (s1 != s3) || (s2 != s3)){
//spin again...
}
To hit the jackpot, we must spin the wheels at least once. This leads to a final, simpler version using a do-while:
do{
s1 = RandomOneOf(['lemon', 'cherry', 'bar', 'donut']);
s2 = RandomOneOf(['lemon', 'cherry', 'bar', 'donut']);
s3 = RandomOneOf(['lemon', 'cherry', 'bar', 'donut']);
}while ((s1 != s2) || (s1 != s3) || (s2 != s3));
The do...while loop will always be executed at least once, even if the condition is false, because the statements are executed before the condition is tested.
It is a
post-test loop; the while loop and the for loop are
pre-test loops.
Use the do-while when you know you will repeat an action at least once.