Scala Solution using Pattern Matching

• ``````class P038_Solution {
private val NUMBER_PATTERN = "[0]+|[1]+|[2]+|[3]+|[4]+|[5]+|[6]+|[7]+|[8]+|[9]+".r

def countAndSay(n: Int): String = {
n match {
case _ if n < 1 => ""
case 1 => display(1, 1)
case _ => convert(countAndSay(n-1).toInt)
}
}

private def display(number: Int, count: Int): String = count.toString + number.toString

private def charToInt(c: Char): Int = Integer.parseInt(c.toString)

private def convert(n: Int): String = {
val numberCounts = (NUMBER_PATTERN findAllIn n.toString).toList
numberCounts
.map(s => display(charToInt(s.charAt(0)), s.length))
}
}
``````

Thought it would be interesting to use Pattern matching to split the repetitions.

• It's better to return a String in convert so countAndSay(30) doesn't throw a NumberFormatException.

``````class P038_Solution {
private val NUMBER_PATTERN = "[0]+|[1]+|[2]+|[3]+|[4]+|[5]+|[6]+|[7]+|[8]+|[9]+".r

def countAndSay(n: Int): String = {
n match {
case _ if n < 1 => ""
case _ =>
var result = convert("1")
for (_ <- 2 to n) {
result = convert(result)
}
result
}
}

private def display(number: Int, count: Int): String = count.toString + number.toString

private def charToInt(c: Char): Int = Integer.parseInt(c.toString)

private def convert(n: String): String = {
(NUMBER_PATTERN findAllIn n).toList
.map(s => display(charToInt(s.charAt(0)), s.length))