Skip to content

Instantly share code, notes, and snippets.

@scottmascio2115
Created August 11, 2013 22:25
Show Gist options
  • Save scottmascio2115/6207165 to your computer and use it in GitHub Desktop.
Save scottmascio2115/6207165 to your computer and use it in GitHub Desktop.

Revisions

  1. scottmascio2115 created this gist Aug 11, 2013.
    70 changes: 70 additions & 0 deletions roman_refactor.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    # 1: Grab a solution to Roman Numerals
    #
    # Source: https://gist.github.com/leeacto/ece0c63cfda0d022b536
    # Author: Nick lee

    # ------------
    # 2. Explain the code in plain English
    # Given a number, translate that number into a roman numeral.
    # You have to create a set of numbers. The assign those numbers letters.
    #Take your original number and run it through the set of numbers.
    #If the number divides into the number in the set put the letter coresponding to
    # that number. If the number divides more than once into the number in the set
    #put a letter representing how many times it divides into it.

    # ------------
    # 3. Translate to pseudocode
    # Create a hash where the key is a number and the value is the letter.
    # Create a variable number that can be tested through each key- value pair
    # Run the number through each key/value pair
    # If the number divides into the key
    #return put the letter value * how many times it divides into the key
    #end if
    #return a string

    # ------------
    # 4. Test the code
    def to_roman_modern(num)
    test_arr = {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"}
    @num = num
    roman = ""

    test_arr.each do |base, rom|
    r_count = @num / base
    roman += rom * r_count
    @num -= r_count * base
    end
    return roman
    end

    # Drive code... this should print out trues.

    puts to_roman_modern(1) == "I"
    puts to_roman_modern(3) == "III"
    puts to_roman_modern(6) == "VI"

    # 5. Refactor
    #
    # Write the refactored method below.
    # Comment out the original so that your tests are run
    # against the refactored version.
    def to_roman_refactor(number)

    romans_hash = {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"}

    #final roman string variable
    roman = ""

    #iterate through hash
    romans_hash.each do |key, value|
    romans_count = number / key
    #push roman numerals into string
    roman << value * romans_count
    #decrementing number
    number -= romans_count * key
    end
    roman
    end
    puts to_roman_refactor(1) == "I"
    puts to_roman_refactor(3) == "III"
    puts to_roman_refactor(6) == "VI"