Skip to content

Instantly share code, notes, and snippets.

@sebnozzi
Created September 10, 2013 10:53
Show Gist options
  • Save sebnozzi/6507801 to your computer and use it in GitHub Desktop.
Save sebnozzi/6507801 to your computer and use it in GitHub Desktop.
In the spirit of this article ( http://java.dzone.com/articles/merits-verbosity-and-flaws ) I wanted to re-write the implementation in a more verbose and readable fashion. Even if the result is not a cool one-liner ;-)
def toRoman( v:Int ) : String = {
val romanNumerals = List(1000->"M",900->"CM",500->"D",400->"CD",100->"C",90->"XC",
50->"L",40->"XL",10->"X",9->"IX",5->"V",4->"IV",1->"I")
var n = v
romanNumerals.foldLeft(""){(s,t) => {val c = n/t._1; n = n-t._1*c; s + (t._2 * c) } }
}
def toRoman(num: Int): String = {
case class RomanUnit(value: Int, token: String)
val romanNumerals = List(
RomanUnit(1000, "M"),
RomanUnit(900, "CM"),
RomanUnit(500, "D"),
RomanUnit(400, "CD"),
RomanUnit(100, "C"),
RomanUnit(90, "XC"),
RomanUnit(50, "L"),
RomanUnit(40, "XL"),
RomanUnit(10, "X"),
RomanUnit(9, "IX"),
RomanUnit(5, "V"),
RomanUnit(4, "IV"),
RomanUnit(1, "I"))
var remainingNumber = num
romanNumerals.foldLeft("") { (outputStr, romanUnit) =>
{
val times = remainingNumber / romanUnit.value
remainingNumber -= romanUnit.value * times
outputStr + (romanUnit.token * times)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment