Finding a passcode by comparing MD5 result This function finds the 8 char passcode from a given "doorId".

Is there a way to find the passcode in an undetermined number of steps without using a while? Maybe involving streams? val passcode = stream(logic).take(8).

def findPassCode(doorId: String): String = {
  var passcode = ""
  var count = 0

  while (passcode.length &lt; 8) {
    val hash = md5(doorId + count)
    if (hash.startsWith("00000")) passcode = passcode + hash.drop(5).take(1)
    count = count + 1
  }

  passcode
}
First of all, you have the passcode length hard-coded.  It would be better to make it a parameter, perhaps with a default value.  The same goes for the string the "interesting" hashes start with ("00000").

Also, there are several ways you could make the code more functional.  Here are a couple ideas:


Use recursion:  Computing an \$n\$ character pascode is accomplished by first computing an \$n-1\$ character passcode, then computing the next character.  Or, you could rewrite the loop in a tail-recursive form.
You could use streams.  Streams are Scala's version of a lazy list / sequence.


Using streams, we can use the following logic:


Generate a stream of consecutive Ints, starting at 0.
Combine each number in with doorId
Compute the hash of each combined string
Filter the hashes, keeping only hashes that start with five '0's
Take the sixth character of each hash
Take the first 8 - doorId.length characters, and append them to doorId


We can express this in code using something like:

def findPassCode(doorId: String): String = {
  val chars = Stream.from(0)                            // Step 1
                    .map(n =&gt; doorId + n)               // Step 2
                    .map(md5)                           // Step 3
                    .filter(h =&gt; h.startsWith("00000")) // Step 4
                    .map(h =&gt; h(5))                     // Step 5
  doorId + chars.take(8 - doorId.length).mkString       // Step 6
}