Created
December 13, 2012 05:35
-
-
Save anonymous/4274296 to your computer and use it in GitHub Desktop.
RomanNumerals Scala
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
| import org.scalatest.FlatSpec | |
| class RomanNumerals private(val number: Int) { | |
| private val keyNumbers = List(50, 10, 5, 1) | |
| private val pairs = Map(1 -> "I", 5 -> "V", 10 -> "X", 50 -> "L") | |
| def roman() = { | |
| val romanHolder = new StringBuilder | |
| var left = number | |
| for (keyNumber <- keyNumbers) { | |
| appendCharacter(romanHolder, left, pairs(keyNumber), keyNumber) | |
| left = left % keyNumber | |
| } | |
| val result = romanHolder.toString() | |
| .replace("VIIII", "IX") | |
| .replace("IIII", "IV") | |
| .replace("XXXX", "XL") | |
| result | |
| } | |
| private def appendCharacter(result: StringBuilder, number: Int, character: String, characterNumber: Int) { | |
| for (i <- 1 to number / characterNumber) { | |
| result.append(character) | |
| } | |
| } | |
| } | |
| object RomanNumerals { | |
| def apply(number: Int) = new RomanNumerals(number) | |
| } | |
| class RomanNumeralsSpec extends FlatSpec { | |
| "Number 1" should "I" in { | |
| assert("I" === RomanNumerals(1).roman) | |
| } | |
| "Number 2" should "II" in { | |
| assert("II" === RomanNumerals(2).roman) | |
| } | |
| "Number 4" should "IV" in { | |
| assert("IV" === RomanNumerals(4).roman) | |
| } | |
| "Number 5" should "V" in { | |
| assert("V" === RomanNumerals(5).roman) | |
| } | |
| "Number 6" should "VI" in { | |
| assert("VI" === RomanNumerals(6).roman) | |
| } | |
| "Number 9" should "IX" in { | |
| assert("IX" === RomanNumerals(9).roman) | |
| } | |
| "Number 10" should "X" in { | |
| assert("X" === RomanNumerals(10).roman) | |
| } | |
| "Number 11" should "XI" in { | |
| assert("XI" === RomanNumerals(11).roman) | |
| } | |
| "Number 14" should "XIV" in { | |
| assert("XIV" === RomanNumerals(14).roman) | |
| } | |
| "Number 15" should "XV" in { | |
| assert("XV" === RomanNumerals(15).roman) | |
| } | |
| "Number 19" should "XIX" in { | |
| assert("XIX" === RomanNumerals(19).roman) | |
| } | |
| "Number 20" should "XX" in { | |
| assert("XX" === RomanNumerals(20).roman) | |
| } | |
| "Number 40" should "XL" in { | |
| assert("XL" === RomanNumerals(40).roman) | |
| } | |
| "Number 50" should "L" in { | |
| assert("L" === RomanNumerals(50).roman) | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment