Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ローマ数字変換 #7

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 56 additions & 2 deletions lib/sg_romanizer.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,63 @@
class SgRomanizer
def romanize(arabic)
# write your code here
raise ArgumentError unless (1..3999).cover?(arabic)

[1000, 100, 10, 1].map do |digit|
romasymbols = digit_to_romasymbols(digit)
adjusted_arabic = arabic % (digit * 10)
coefficient = (adjusted_arabic / digit).to_i
romanize_format(coefficient, romasymbols)
end.join
end

def deromanize(roman)
# write your code here
raise ArgumentError unless roman.match?(/^[MDCLXVI]+$/)

roman.split('').push('-').each_cons(2).map do |symbols|
num = romasymbol_to_num(symbols[0])
next_num = romasymbol_to_num(symbols[1])
num < next_num ? -num : num
end.sum
end

private

def digit_to_romasymbols(digit)
case digit
when 1000 then ['M', nil, nil]
when 100 then ['C', 'D', 'M']
when 10 then ['X', 'L', 'C']
when 1 then ['I', 'V', 'X']
else []
end
end

def romanize_format(num, symbols)
i,v,x = symbols
case num
when 1 then i
when 2 then i + i
when 3 then i + i + i
when 4 then i + v
when 5 then v
when 6 then v + i
when 7 then v + i + i
when 8 then v + i + i + i
when 9 then i + x
else ''
end
end

def romasymbol_to_num(symbol)
case symbol
when 'M' then 1000
when 'D' then 500
when 'C' then 100
when 'L' then 50
when 'X' then 10
when 'V' then 5
when 'I' then 1
else 0
end
end
end