Created
February 27, 2017 22:00
-
-
Save cjhowald/3fbbd6e77fc0caf2f033b5bd1a5cd7ef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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