import scala.collection.SortedMap
object Raindrops {
private val sound = SortedMap(
3 -> "Pling",
5 -> "Plang",
7 -> "Plong"
)
def convert(n: Int): String =
sound.filterKeys(n % _ == 0).values match {
case drops if (!drops.isEmpty) => drops.mkString
case _ => n.toString
}
}
This approach starts by defining a SortedMap with the numbers for keys and the sounds for values.
The filterKeys() method is called on the SortedMap.
Each key is passed to the lambda, where the input number is tested to be evenly divisible by the key.
Those keys by which the input number can be evenly divided have their values passed to the match, where the values are checked for being empty.
If not empty, then the mkString method is used to return the values as a String from the convert() method.
Otherwise, if there are no matching keys, then the values will be empty, and the match returns the original number as a String from the convert() method.
16th Aug 2024
·
Found it useful?