 # Ric0chet's solution

## to Roman Numerals in the Scala Track

Published at Oct 15 2019 · 0 comments
Instructions
Test suite
Solution

Write a function to convert from normal numbers to Roman Numerals.

The Romans were a clever bunch. They conquered most of Europe and ruled it for hundreds of years. They invented concrete and straight roads and even bikinis. One thing they never discovered though was the number zero. This made writing and dating extensive histories of their exploits slightly more challenging, but the system of numbers they came up with is still in use today. For example the BBC uses Roman numerals to date their programmes.

The Romans wrote numbers using letters - I, V, X, L, C, D, M. (notice these letters have lots of straight lines and are hence easy to hack into stone tablets).

`````` 1  => I
10  => X
7  => VII
``````

There is no need to be able to convert numbers larger than about 3000. (The Romans themselves didn't tend to go any higher)

Wikipedia says: Modern Roman numerals ... are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero.

To see this in practice, consider the example of 1990.

In Roman numerals 1990 is MCMXC:

1000=M 900=CM 90=XC

2008 is written as MMVIII:

2000=MM 8=VIII

## Hints

For something a little different you might also try a solution with an `unfold` function. You are probably already familiar with `foldLeft/Right`: "map" a whole collection into something else (usually a non-collection). `unfoldLeft/Right` are the "inverse" operations: "map" something (usually a non-collection) into a collection. So `unfold`ing is a logical addition to and part of the FP standard repertoire.

This exercise can be seen as a case for `unfold`ing: "map" an `Int` into a `String` (which is of course implicitly a `Seq[Char]`).

Unfortunately `unfoldLeft/Right` is not included in Scala's collection library. But you can take the implementation from here.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test` in the exercise directory.

Please see the learning and installation pages if you need any help.

## Source

The Roman Numeral Kata http://codingdojo.org/cgi-bin/index.pl?KataRomanNumerals

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### RomanNumeralsTest.scala

``````import org.scalatest.{Matchers, FunSuite}

/** @version 1.2.0 */
class RomanNumeralsTest extends FunSuite with Matchers {

test("1 is a single I") {
RomanNumerals.roman(1) should be ("I")
}

test("2 is two I's") {
pending
RomanNumerals.roman(2) should be ("II")
}

test("3 is three I's") {
pending
RomanNumerals.roman(3) should be ("III")
}

test("4, being 5 - 1, is IV") {
pending
RomanNumerals.roman(4) should be ("IV")
}

test("5 is a single V") {
pending
RomanNumerals.roman(5) should be ("V")
}

test("6, being 5 + 1, is VI") {
pending
RomanNumerals.roman(6) should be ("VI")
}

test("9, being 10 - 1, is IX") {
pending
RomanNumerals.roman(9) should be ("IX")
}

test("20 is two X's") {
pending
RomanNumerals.roman(27) should be ("XXVII")
}

test("48 is not 50 - 2 but rather 40 + 8") {
pending
RomanNumerals.roman(48) should be ("XLVIII")
}

test("49 is not 40 + 5 + 4 but rather 50 - 10 + 10 - 1") {
pending
RomanNumerals.roman(49) should be ("XLIX")
}

test("50 is a single L") {
pending
RomanNumerals.roman(59) should be ("LIX")
}

test("90, being 100 - 10, is XC") {
pending
RomanNumerals.roman(93) should be ("XCIII")
}

test("100 is a single C") {
pending
RomanNumerals.roman(141) should be ("CXLI")
}

test("60, being 50 + 10, is LX") {
pending
RomanNumerals.roman(163) should be ("CLXIII")
}

test("400, being 500 - 100, is CD") {
pending
RomanNumerals.roman(402) should be ("CDII")
}

test("500 is a single D") {
pending
RomanNumerals.roman(575) should be ("DLXXV")
}

test("900, being 1000 - 100, is CM") {
pending
RomanNumerals.roman(911) should be ("CMXI")
}

test("1000 is a single M") {
pending
RomanNumerals.roman(1024) should be ("MXXIV")
}

test("3000 is three M's") {
pending
RomanNumerals.roman(3000) should be ("MMM")
}
}``````
``````import scala.collection.immutable.ListMap
//  10-14-19

object RomanNumerals {
def roman(num: Int): String =
usingMapping(num)
//  usingFolding(num)
//  usingUnfolding(num)
//  usingRecursion(num)
//  usingMultiDim(num)

// Map used by all, but the last solution
private val romanMap = ListMap[Int, String](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")

// 53 ms
private def usingMapping(num: Int): String = {
var n = num
var acc = ""
romanMap.foreach { case (key, value) =>
(0 until n / key).foreach { _ =>
n -= key
acc += value
}
}
acc
}

// 45 ms -- same algorithm as above, but FASTER
private def usingFolding(num: Int): String = {
var n = num
romanMap.foldLeft("") { (acc, pair) =>
acc + (0 until n / pair._1).fold("") { (digits, _) =>
n -= pair._1
digits + pair._2
}
}
}

// 48 ms
private def usingUnfolding(num: Int): String = unfoldRight(num) { n =>
romanMap.find { _._1 <= n }.map { case (k, v) => (v, n - k) }
}.mkString

private def unfoldRight[A, B](seed: B)(f: B => Option[(A, B)]): List[A] =
f(seed) match {
case Some((a, b)) => a :: unfoldRight(b)(f)
case None => Nil
}

// 65 ms -- a bit SLOWER, due to repeated filter traversals
@annotation.tailrec
private def usingRecursion(num: Int, acc: String = ""): String =
if (num == 0) acc
else {
val key = romanMap.keys.filter { _ <= num }.max
usingRecursion(num - key, acc ++ romanMap(key))
}

// Multi-dim array for final solution
private val romanDigits = Array[Array[String]](
Array("I", "V", "X"),
Array("X", "L", "C"),
Array("C", "D", "M"),
Array("M", "M", "M")
)

// 47 ms
private def usingMultiDim(num: Int): String = {
var n = num
var place = 0
var acc = ""
while (n > 0) {
val places = romanDigits(place)
acc = digitToRoman(n % 10, places(0), places(1), places(2)) + acc
place += 1
n /= 10
}
acc
}

private def digitToRoman(digit: Int, low: String, med: String, high: String): String =
digit match {
case 1 => low
case 2 => low + low
case 3 => low + low + low
case 4 => low + med
case 5 => med
case 6 => med + low
case 7 => med + low + low
case 8 => med + low + low + low
case 9 => low + high
case _ => ""
}

}``````