Roman Numeral in Euphoria

Published on 25 February 2023 (Updated: 25 February 2023)

Welcome to the Roman Numeral in Euphoria page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

include std/io.e

procedure usage()
    puts(STDOUT, "Usage: please provide a string of roman numerals\n")
end procedure

procedure error()
    puts(STDOUT, "Error: invalid string of roman numerals\n")
end procedure

-- Roman numeral table
sequence romans = {
    {'M', 1000},
    {'D', 500},
    {'C', 100},
    {'L', 50},
    {'X', 10},
    {'V', 5},
    {'I', 1}

-- Indices for roman numeral table

-- Get value of Roman letter
function get_roman(integer letter)
    for k = 1 to length(romans)
        if letter = romans[k][ROMAN_LETTER]
            return romans[k][ROMAN_VALUE]
        end if
    end for

    return 0
end function

-- Convert Roman numeral to a value
function roman_number(sequence s)
    integer total = 0
    integer prev_value = -1 -- No previous value
    for k = 1 to length(s)
        -- Get value of current letter. If not found, indicate invalid and exit
        integer value = get_roman(s[k])
        if value < 1
            return -1
        end if

        -- Add value to total
        total += value

        -- If there is a previous value and value is greater than previous value,
        -- subtract two times previous value from total to compensate for addition of
        -- previous value -- e.g., if previous value was 100 (C) and current value is
        -- 1000 (M), the total currently equals 1100, but we want it to be 900 (1100 - 2*100).
        -- Also, reset the current value so that there is no previous value
        if prev_value > 0 and value > prev_value
            total -= 2 * prev_value
            value = -1
        end if

        -- Store current value to previous value
        prev_value = value
    end for

    return total
end function

-- If too few arguments, exit
sequence argv = command_line()
if length(argv) < 4
end if

-- Convert Roman numeral to value
sequence s = argv[4]
integer value = roman_number(s)
if value >= 0
    printf(STDOUT, "%d\n", {value})
end if

Roman Numeral in Euphoria was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.