-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathromanconvertor.rb
111 lines (95 loc) · 2.47 KB
/
romanconvertor.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#Author: Chris Bucker
def fromRoman(romanNumber)
romanNumerals = ["I", "V", "X", "L", "C", "D", "M"]
finalValue = 0
for letter in romanNumber.chars
if !romanNumerals.include? letter
raise TypeError
end
end
mValue,index = fromLoop("M",romanNumber,1000)
cValue,index = fromLoop("C",romanNumber,100,index)
xValue,index = fromLoop("X",romanNumber,10,index)
iValue,index = fromLoop("I",romanNumber,1,index)
return finalValue = mValue + cValue + xValue + iValue
end
def fromLoop(requestedLetter, romanNumber, value, index = 0)
endValue = 0
halfNumeral = getHalf(requestedLetter)
nextNumeral = getNext(requestedLetter)
if romanNumber[index] != requestedLetter
if romanNumber[index] == halfNumeral
endValue = value*5
index += 1
else
return endValue, index
end
end
for letter in romanNumber.chars[index..romanNumber.chars.length-1]
if letter == requestedLetter
endValue += value
index += 1
elsif letter == halfNumeral
endValue += value*3
index += 1
break
elsif letter == nextNumeral
endValue += value*8
index += 1
break
end
end
return endValue, index
end
def toRoman(arabicNumber)
romanNumber = ""
if arabicNumber >= 4000 || arabicNumber <= 0
raise RangeError
end
numberOfStartM = arabicNumber/1000.0
numberOfStartC = (arabicNumber - numberOfStartM.floor()*1000.0) / 100.0
numberOfStartX = (numberOfStartC*100.0 - numberOfStartC.floor()*100.0) / 10.0
numberOfStartI = numberOfStartX*10.0 - numberOfStartX.floor()*10.0
romanNumber = "M"*numberOfStartM.floor()
romanNumber = romanNumber + checkToRoman(numberOfStartC, "C")
romanNumber = romanNumber + checkToRoman(numberOfStartX, "X")
romanNumber = romanNumber + checkToRoman(numberOfStartI, "I")
return romanNumber
end
def checkToRoman(numberOfLetter, letter)
numberOfLetter = numberOfLetter.floor()
halfNumeral = getHalf(letter)
nextNumeral = getNext(letter)
if numberOfLetter <=3
return letter*numberOfLetter
end
if numberOfLetter == 4
return letter + halfNumeral
elsif numberOfLetter == 9
return letter + nextNumeral
else
return halfNumeral + letter*(numberOfLetter-5)
end
end
def getHalf(letter)
halfNumeral = ""
if letter == "C"
halfNumeral = "D"
elsif letter == "X"
halfNumeral = "L"
elsif letter == "I"
halfNumeral = "V"
end
return halfNumeral
end
def getNext(letter)
nextNumeral = ""
if letter == "C"
nextNumeral = "M"
elsif letter == "X"
nextNumeral = "C"
elsif letter == "I"
nextNumeral = "X"
end
return nextNumeral
end