Skip to content

Instantly share code, notes, and snippets.

@lhoang
Created April 29, 2019 15:34
Show Gist options
  • Save lhoang/a423f47b0d2f96a107429d163bf1c5d5 to your computer and use it in GitHub Desktop.
Save lhoang/a423f47b0d2f96a107429d163bf1c5d5 to your computer and use it in GitHub Desktop.
Roman Numbers in Scala
def roman(n: Int) = {
def div(v: Int, d: Int) : (Int, Int) = (v / d, v % d)
val romanMap = 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")
)
val (_, res) = romanMap.foldLeft((n, ""))((acc, elt) => {
val (diviser, letter) = elt
val (rest, tempResult) = acc
val (q, r) = div(rest, diviser)
(r, tempResult + letter * q)
})
res
}
roman(3)
roman(4)
roman(9)
roman(12)
roman(69)
roman(22)
roman(16)
roman(2569)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment