Scala code to solve a puzzle