開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- Ruby (プログラミング言語)
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 9章(自作メソッドの書き方), 9.5(練習問題)、古典的ローマ数字、を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
古典的ローマ数字
コード(BBEdit)
sample.rb
#!/usr/bin/env ruby2.0 #-*- coding: utf-8 -*- def old_roman_numeral num num_roman = {1000 => 'M', 500 => 'D', 100 => 'C', 50 => 'L', 10 => 'X', 5 => 'V', 1 => 'I'} result = "" num_roman.each do |n, c| result += c * (num / n) num %= n end result end puts old_roman_numeral 4 puts old_roman_numeral 9 (100..120).each do |n| puts "#{n}: #{old_roman_numeral n}" end
入出力結果(Terminal)
$ ./sample.rb IIII VIIII 100: C 101: CI 102: CII 103: CIII 104: CIIII 105: CV 106: CVI 107: CVII 108: CVIII 109: CVIIII 110: CX 111: CXI 112: CXII 113: CXIII 114: CXIIII 115: CXV 116: CXVI 117: CXVII 118: CXVIII 119: CXVIIII 120: CXX $
ちなみにpython3.3の場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def oldRomanNumeral(num): num_roman = { 1000:'M', 500:'D', 100:'C', 50:'L', 10:'X', 5:'V', 1:'I' } result = "" for n in sorted(num_roman.keys(), reverse=True): result += num_roman[n] * (num // n) num %= n return result print(oldRomanNumeral(4)) print(oldRomanNumeral(9)) for n in range(100, 121): print('{0}: {1}'.format(n, oldRomanNumeral(n)))
入出力結果(Terminal)
$ ./sample.py IIII VIIII 100: C 101: CI 102: CII 103: CIII 104: CIIII 105: CV 106: CVI 107: CVII 108: CVIII 109: CVIIII 110: CX 111: CXI 112: CXII 113: CXIII 114: CXIIII 115: CXV 116: CXVI 117: CXVII 118: CXVIII 119: CXVIIII 120: CXX $
0 コメント:
コメントを投稿