Skip to content

Instantly share code, notes, and snippets.

@sway
Created December 1, 2012 17:21
Show Gist options
  • Save sway/4183333 to your computer and use it in GitHub Desktop.
Save sway/4183333 to your computer and use it in GitHub Desktop.

Revisions

  1. Honza Ustohal created this gist Dec 1, 2012.
    49 changes: 49 additions & 0 deletions 01_arabic_roman.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    $map = {
    'M' => 1000,
    'CM' => 900,
    'D' => 500,
    'CD' => 400,
    'C' => 100,
    'XC' => 90,
    'L' => 50,
    'XL' => 40,
    'X' => 10,
    'IX' => 9,
    'V' => 5,
    'IV' => 4,
    'I' => 1
    }

    def is_int?(s)
    s =~ /^-?[0-9]+$/
    end

    def to_arabic(s)
    output = 0
    $map.each do |k, v|
    while s.start_with?(k)
    output += v
    s.slice!(k)
    end
    end
    return output
    end

    def to_roman(i)
    output = ""
    $map.each do |k, v|
    while i >= v
    output << k
    i -= v
    end
    end
    return output
    end

    while input = gets
    if is_int?(input)
    puts to_roman(input.to_i)
    else
    puts to_arabic(input)
    end
    end