Generate a sequence of coin flips until pattern is hit A book on probability says that a sequence of heads and tails is generated by a fair coin asking what is the probability that the pattern T, H, H, H occurs before the pattern H, H, H, H. I have made a generator of such strings. Is it right (I have heard that return statement is not appreciated in Scala)?

def l(s: String): Boolean = {
    if (s.endsWith("hhhh")) return true; 
    if (s.endsWith("thhh")) return false; 
    l(s + (if (Math.random &gt; .5) "h" else "t"))
}
To avoid return statements:

def l(s: String): Boolean = {
  if (s.endsWith("hhhh")) true
  else if (s.endsWith("thhh")) false
  else l(s + (if (Math.random &gt; .5) "h" else "t"))
}


Although I don't like if - else if sequences, in this case it remains simple and readable, but it still can be simplified like this

def l(s: String): Boolean = {
  if (s.length &gt; 3) s.endsWith("hhhh")
  else l(s + (if (Math.random &gt; .5) "h" else "t"))
}


or even

def l(s: String): Boolean = {
  s.endsWith("hhhh") || l(s + (if (Math.random &gt; .5) "h" else "t"))
}


Randomness

I think that there is a minor issue with random values distribution.

As per Scaladoc for Math.random:


  Returns a Double value with a positive sign, greater than or equal to 0.0 and less than 1.0.


For the current condition, this means that 0.5 &lt; h &lt; 1.0 and 0 &lt;= t &lt;= 0.5.

0.5 is not included in the lower bound for generation of h values, which favors t very slightly.

The condition for equal distribution should be if (Math.random &lt; 0.5) "t" else "h".