Created
April 4, 2013 10:16
-
-
Save stianeikeland/5309302 to your computer and use it in GitHub Desktop.
Bergen coding dojo - Roman numerals
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
_ = require 'underscore' | |
class FromRomanNumerals | |
baseValues: { | |
"I": 1 | |
"V": 5 | |
"X": 10 | |
"L": 50 | |
"C": 100 | |
"D": 500 | |
"M": 1000 | |
} | |
parse: (roman, prev = 1) -> | |
head = _.head roman | |
tail = _.tail roman | |
sign = if prev > head then -1 else 1 | |
if roman.length is 1 then sign * head else sign * head + (@parse tail, head) | |
parseRoman: (roman) -> | |
# Convert to numbers, reverse and parse | |
@parse (_.map roman, (x) => @baseValues[x]).reverse() | |
module.exports = FromRomanNumerals | |
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
_ = require 'underscore' | |
class RomanNumerals | |
baseValues: { | |
1: "I" | |
5: "V" | |
10: "X" | |
50: "L" | |
100: "C" | |
500: "D" | |
1000: "M" | |
} | |
# Stupid fudge factor since romans wrote VIII instead of IIX | |
# Going for the closest one also selects the shortest (IIX over VIII) | |
fudgeFactor: (num) -> | |
strNum = String(num) | |
return (-1 * (Math.pow 10, strNum.length - 1)) if strNum[0] in ['3', '8'] | |
return 0 | |
getClosestNumeral: (num) -> | |
parseInt (_.min (Object.keys @baseValues), (x) => | |
Math.abs(num - x + @fudgeFactor num)) | |
isBaseValue: (num) -> | |
@baseValues[num]? | |
getBaseValue: (num) -> | |
@baseValues[num] | |
getRomanNumeral: (num) -> | |
return @getBaseValue num if @isBaseValue num | |
closest = @getClosestNumeral num | |
diff = num - closest | |
return "#{@getRomanNumeral (Math.abs diff)}#{@getBaseValue closest}" if diff < 0 | |
return "#{@getBaseValue closest}#{@getRomanNumeral (Math.abs diff)}" | |
parseNumberToRoman: (num) -> | |
input = String(num) | |
position = input.length - 1 | |
result = "" | |
for i in input | |
result += @getRomanNumeral(i * Math.pow 10, position) if i > 0 | |
position-- | |
result | |
module.exports = RomanNumerals |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mocha tester: