Created
April 25, 2012 14:44
-
-
Save kei-q/2490269 to your computer and use it in GitHub Desktop.
shinjuku.rbでもくもくと書いてたコード 負の数を入れたら挙動おかしいね
This file contains hidden or 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
# digit : 一桁の数字 | |
# roman : その桁の1, 5, 10を表す文字三文字 (ex: 'IVX') | |
def digit2roman(digit, roman) | |
a, b, c = roman.split(//) | |
case digit | |
when 0 then '' | |
when 1..3 then a * digit | |
when 4 then a + b | |
when 5 then b | |
when 6..8 then b + a * (digit - 5) | |
when 9 then a + c | |
end | |
end | |
ROMAN_WORDS = 'IVXLCDM ' | |
def _roman(num, place) | |
(num >= 10 ? _roman(num/10, place+1) : '') + digit2roman(num%10, ROMAN_WORDS[place*2, 3]) | |
end | |
# num : 変換したい数値 | |
# ただし1から3999まで | |
# | |
# 0を入れた場合は空文字が返される | |
# 4000以上のときは未定義 | |
def roman(num) | |
_roman(num, 0) | |
end | |
# 動作確認用メソッド | |
# 結果が正しく無いときはメッセージを表示する | |
# 全て期待通りならなにも表示しない | |
def a(actual, expect) | |
ret = roman(actual) | |
unless ret == expect | |
puts "NG: #{actual}, #{expect}, #{ret}" | |
end | |
end | |
# 以下テストケース | |
a(1, 'I') | |
a(2, 'II') | |
a(3, 'III') | |
a(4, 'IV') | |
a(5, 'V') | |
a(6, 'VI') | |
a(7, 'VII') | |
a(8, 'VIII') | |
a(9, 'IX') | |
a(10, 'X') | |
a(11, 'XI') | |
a(14, 'XIV') | |
a(50, 'L') | |
a(100, 'C') | |
a(500, 'D') | |
a(1999, 'MCMXCIX') | |
a(3999, 'MMMCMXCIX') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment