Skip to content

Instantly share code, notes, and snippets.

@cjhowald
Created February 27, 2017 22:00
Show Gist options
  • Save cjhowald/3fbbd6e77fc0caf2f033b5bd1a5cd7ef to your computer and use it in GitHub Desktop.
Save cjhowald/3fbbd6e77fc0caf2f033b5bd1a5cd7ef to your computer and use it in GitHub Desktop.
object RomanNumerals {
val digitsToNumerals = Map(
1 -> "I",
5 -> "V",
10 -> "X",
50 -> "L",
100 -> "C",
500 -> "D",
1000 -> "M"
)
def convert(int: Int): String =
digitsToNumerals
.toSeq // convert to sequence so we can sort
.sortWith(_._1 > _._1) // sort high to low by key
.foldLeft(int -> "") { // reduce (int, "") with the map to (0, numerals)
case ((remain, numerals), (digit, numeral)) => // pattern match to destructure inputs
(remain % digit, numerals + numeral * (remain / digit)) // divide remain by digit, build result, shrink remain
}._2 // return the numeral
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment