-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem89.rb
67 lines (61 loc) · 1.01 KB
/
problem89.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
require 'euler_helper.rb'
ROMAN = {
1 => 'I',
5 => 'V',
10 => 'X',
50 => 'L',
100 => 'C',
500 => 'D',
1000 => 'M',
4 => 'IV',
9 => 'IX',
40 => 'XL',
90 => 'XC',
400 => 'CD',
900 => 'CM'
}
def romanize n
keys = ROMAN.keys.sort
r = ''
while n > 0
if n >= keys.last
r += ROMAN[keys.last]
n -= keys.last
else
keys.pop
end
end
r
end
def parse_roman roman
inv_roman = ROMAN.invert
r = 0
while roman.size > 0
if inv_roman.key?(roman[0..1])
r += inv_roman[roman[0..1]]
if roman.size > 2
roman = roman[2..-1]
else
roman = ''
end
else
r += inv_roman[roman[0..0]]
if roman.size > 1
roman = roman[1..-1]
else
roman = ''
end
end
end
r
end
def compact roman
romanize(parse_roman(roman))
end
def solve
numbers = File.read('roman.txt').split(/\n/).map!(&:strip)
numbers.inject(0) {|memo, n| memo += (n.size - compact(n).size)}
end
benchmark do
puts solve.inspect
end