2

I'm new to php and am trying to write a loop that will flip a coin until exactly two heads have been flipped and then stop.

So far I've written a function for coin flipping:

function cointoss () {
    $cointoss = mt_rand(0,1);
    $headsimg = '<img src=""/>';
    $tailsimg = '<img src=""/>';
    if ($cointoss == 1){
        print $headsimg;
    } else {
        print $tailsimg;
    } 
    return $cointoss;
}

...but am stuck on writing the loop. I've tried a couple ways:

#this code takes forever to load
$twoheads = 0;
for ($twoheads = 1 ; $twoheads <= 20; $twoheads++) {
    $cointoss = mt_rand(0,1);
    cointoss ();
    if ($cointoss == 1) { 
        do {
        cointoss ();
    } while ($cointoss == 1);

    }
}

#one coin flips 
do {
    cointoss ();
} while ($cointoss == 1);

This is a for a class, and we haven't learned arrays yet, so I need to accomplish this without them.

I understand the concept of loops executing code while a condition is true, but don't understand how to write for when a condition is no longer true.

pzstein
  • 35
  • 3

1 Answers1

2

Printing from inside of "processing functions" is a bad habit to get into. You might like to declare a showCoin($toss) function for printing. In truth, I don't know if I would bother with any custom functions.

You need to declare a variable which will hold the return value from your function.

By storing the current and previous toss values, you can write a simple check if two consecutive "heads" have occurred.

Code: (Demo)

function cointoss () {
    return mt_rand(0,1);  // return zero or one
}

$previous_toss = null;
$toss = null;
do {
    if ($toss !== null) {  // only store a new "previous_toss" if not the first iteration
        $previous_toss = $toss;  // store last ieration's value
    }
    $toss = cointoss();  // get current iteration's value
    echo ($toss ? '<img src="heads.jpg"/>' : '<img src="tails.jpg"/>') , "\n";
    //    ^^^^^- if a non-zero/non-falsey value, it is heads, else tails
} while ($previous_toss + $toss != 2);
//       ^^^^^^^^^^^^^^^^^^^^^^- if 1 + 1 then 2 breaks the loop

Possible Output:

<img src="heads.jpg"/>
<img src="tails.jpg"/>
<img src="tails.jpg"/>
<img src="tails.jpg"/>
<img src="heads.jpg"/>
<img src="heads.jpg"/>
mickmackusa
  • 33,121
  • 11
  • 58
  • 86