Last active
January 21, 2018 21:16
-
-
Save audunolsen/29ea9d1b769855806dd9e6d71c571a10 to your computer and use it in GitHub Desktop.
Short script written in CoffeeScript which converts a string containing roman numerals to an integer
This file contains 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
### Convert string of roman numerals to an integer ### | |
convertSingleChar = (romanNumeral) -> | |
switch romanNumeral | |
when "I" then 1 | |
when "V" then 5 | |
when "X" then 10 | |
when "L" then 50 | |
when "C" then 100 | |
when "D" then 500 | |
when "M" then 1000 | |
nextIntBigger = (array, index) -> | |
if index + 1 is array.length then return false | |
return array[index] < array[index + 1] | |
romanToInt = (romanNumerals) -> | |
intArr = [] | |
intArr.push convertSingleChar romanNumeral for romanNumeral in romanNumerals | |
total = subtractTotal = 0 | |
for int, i in intArr | |
if nextIntBigger intArr, i then subtractTotal += int else total += int | |
return total - subtractTotal | |
console.log romanToInt "LXXXIX" # 89 | |
console.log romanToInt "XCIV" # 94 | |
console.log romanToInt "DCCC" # 800 | |
console.log romanToInt "CM" # 900 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment