Last active
February 4, 2016 14:19
-
-
Save ddeveloperr/a0c69e10ac8b6caf78d4 to your computer and use it in GitHub Desktop.
How to Convert Roman to any number in Ruby
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
| # Define method | |
| def romanize(num) | |
| # define values with hash | |
| digits = { | |
| 1000 => "M", | |
| 900 => "CM", 500 => "D", 400 => "CD", 100 => "C", | |
| 90 => "XC", 50 => "L", 40 => "XL", 10 => "X", | |
| 9 => "IX", 5 => "V", 4 => "IV", 1 => "I" | |
| } | |
| # Check | |
| digits.reduce("") do |acc, digit| | |
| key, numeral = digit | |
| occurances, num = num.divmod(key) | |
| acc + (numeral * occurances) | |
| end | |
| end | |
| romanize 199 | |
| ## Refactored version | |
| @digits = { | |
| 1000 => "M", | |
| 900 => "CM", 500 => "D", 400 => "CD", 100 => "C", | |
| 90 => "XC", 50 => "L", 40 => "XL", 10 => "X", | |
| 9 => "IX", 5 => "V", 4 => "IV", 1 => "I" | |
| } | |
| def romanize(num) | |
| @digits.keys.each_with_object('') do |key, str| | |
| nbr, num = num.divmod(key) | |
| str << @digits[key]*nbr | |
| end | |
| end | |
| romanize(888) # => "DCCCLXXXVIII" | |
| #romanize(999) # => "CMXCIX" | |
| ## Another imrovement using recursion | |
| def romanize(num, str='') | |
| return str if num == 0 | |
| key = @digits.keys.find { |k| k <= num } | |
| str << @digits[key] | |
| romanize(num-key, str) | |
| end | |
| romanize(888) # => "DCCCLXXXVIII" | |
| romanize(999) # => "CMXCIX" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment