Sha256: 353081ec363bb29424984760595a6cdbd9d4f2976644c953555ca8857290b99f

Contents?: true

Size: 1.09 KB

Versions: 3

Compression:

Stored size: 1.09 KB

Contents

module CousinRoman
  module Arabian
    extend self

    def valid?(number)
      number.is_a? Integer and number >= 1 and number <= 3999
    end

    def to_roman(arabian)
      convert arabian if valid? arabian
    end

    def to_roman!(arabian)
      if valid? arabian
        convert arabian
      else
        raise TypeError, 'not a valid roman number'
      end
    end

    def convert(number)
      thousands = number / 1000
      hundreds = number / 100 % 10
      tens = number / 10 % 10
      ones = number % 10

      build_roman(thousands, hundreds, tens, ones).upcase
    end

    def build_roman(thousands, hundreds, tens, ones)
      build_pow(thousands, 3) +
      build_pow(hundreds, 2) +
      build_pow(tens, 1) +
      build_pow(ones, 0)
    end

    def build_pow(number, pow)
      literals = CousinRoman.literals_for_pow pow

      case number
      when 1..3 then literals[:one]*number
      when 4 then literals[:subtractives][4]
      when 5..8 then literals[:five] + (literals[:one]*(number - 5))
      when 9 then literals[:subtractives][9]
      else ""
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
cousin_roman-1.0.7 lib/cousin_roman/arabian.rb
cousin_roman-1.0.6 lib/cousin_roman/arabian.rb
cousin_roman-1.0.5 lib/cousin_roman/arabian.rb