Created
November 2, 2017 06:42
-
-
Save rajeevprasanna/d36ef9e0582073a1ab1ba6aa03620daa to your computer and use it in GitHub Desktop.
roman to integer conversion
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
/** | |
* Created by rajeevprasanna on 11/2/17. | |
*/ | |
object test extends App { | |
// I -> 1 | |
// V -> 5 | |
// X -> 10 | |
// L -> 50 | |
// C -> 100 | |
// D -> 500 | |
// M -> 1000 | |
val romanNumbersMap = List( | |
(1, "I"), | |
(4, "IV"), | |
(5, "V"), | |
(9, "IX"), | |
(10, "X"), | |
(40, "XL"), | |
(50, "L"), | |
(90, "XC"), | |
(100, "C"), | |
(400, "CD"), | |
(500, "D"), | |
(900, "CM"), | |
(1000, "M") | |
) | |
def reduceToRoman(a:Int, res:String, romanNumberVal:Int, romanStr:String):(Int, String) = { | |
if(a >= romanNumberVal){ | |
reduceToRoman(a-romanNumberVal, res+romanStr, romanNumberVal, romanStr) | |
}else{ | |
(a, res) | |
} | |
} | |
def intToRoman(num:Int):String = romanNumbersMap.reverse.foldLeft((num, ""))((res, elem) => reduceToRoman(res._1, res._2, elem._1, elem._2))._2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment