-
-
Save sgronblo/2952682 to your computer and use it in GitHub Desktop.
Convert Kanji numerical to roman numerical
This file contains 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
# Encoding: UTF-8 | |
module KanjiToNumber | |
MULTIPLIERS = {'十' => 10, '百' => 100, '千' => 1000, '万' => 10000} | |
NUM_FOR_NUM = {'壱' => 1, '一' => 1, '1' => 1, | |
'弐' => 2, '二' => 2, '2' => 2, | |
'参' => 3, '三' => 3, '3' => 3, | |
'四' => 4, '4' => 4, | |
'五' => 5, '5' => 5, | |
'六' => 6, '6' => 6, | |
'七' => 7, '7' => 7, | |
'八' => 8, '8' => 8, | |
'九' => 9, '9' => 9, | |
'零' => 0, '〇' => 0, '0' => 0} | |
def self.convert(kanji_number) | |
full_number = 0 | |
current_number = 0 | |
kanji_number.each_char do |kanji| | |
if NUM_FOR_NUM.has_key?(kanji) | |
number = NUM_FOR_NUM[kanji] | |
current_number = current_number * 10 + number | |
elsif MULTIPLIERS.has_key?(kanji) | |
if current_number == 0 # Implicit "one" before hundred or thousand for example | |
full_number += MULTIPLIERS[kanji] | |
else | |
full_number += current_number * MULTIPLIERS[kanji] | |
end | |
current_number = 0 | |
end | |
end | |
full_number += current_number | |
end | |
end | |
require 'minitest/autorun' | |
class KanjiToNumberTest < MiniTest::Unit::TestCase | |
def test_convert | |
assert_equal 2012, KanjiToNumber.convert('二千十二') | |
assert_equal 2012, KanjiToNumber.convert('二〇一二') | |
assert_equal 2012, KanjiToNumber.convert('二〇一二') | |
assert_equal 2222, KanjiToNumber.convert('二千二百二十二') | |
assert_equal 2022, KanjiToNumber.convert('二千二十二') | |
assert_equal 2002, KanjiToNumber.convert('二千二') | |
assert_equal 2000, KanjiToNumber.convert('二千') | |
assert_equal 1000, KanjiToNumber.convert('千') | |
assert_equal 2220, KanjiToNumber.convert('二千二百二十') | |
assert_equal 2200, KanjiToNumber.convert('二千二百') | |
assert_equal 2002, KanjiToNumber.convert('二千二') | |
assert_equal 1222, KanjiToNumber.convert('千二百二十二') | |
assert_equal 222, KanjiToNumber.convert('二百二十二') | |
assert_equal 122, KanjiToNumber.convert('百二十二') | |
assert_equal 321, KanjiToNumber.convert('三二一') | |
assert_equal 4321, KanjiToNumber.convert('四三二一') | |
assert_equal 10001, KanjiToNumber.convert('万一') | |
assert_equal 10001, KanjiToNumber.convert('一万一') | |
assert_equal 240001, KanjiToNumber.convert('24万一') | |
assert_equal 11110, KanjiToNumber.convert('万千百十') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment