Challenge #9 – Roman Numerals

31 August 2020 Closed Twig Intermediate

Given a number, calculate its corresponding Roman numeral using a twig macro.

Challenge

The challenge is to write a macro that takes a number as a parameter and outputs the number converted to a Roman numeral. For example:

4 => IV

61 => LXI

549 => DXLIX

Here is an algorithm that you can follow:

  1. Find the largest Roman numeral that a given number is greater or equal to.
  2. Output the Roman numeral found and decrement its value from the given number.
  3. Repeat the process until the number is less than or equal to zero.

Roman numerals

Below is some twig code to get you started:

{% set number = random(1000) %}

{{ number }} => {{ _self.convertToRomanNumerals(number) }}


{% macro convertToRomanNumerals(number) %}

    {% set romanNumerals = { I: 1, IV: 4, V: 5, IX: 9, X: 10, XL: 40, L: 50, XC: 90, C: 100, CD: 400, D: 500, CM: 900, M: 1000 } %}

{% endmacro %}

For bonus points, minimise the number of times that the algorithm must repeat the process.

Rules

The solution should be written using native twig tags only, so you can use twigfiddle.com to work on and solve the challenge. The code will be evaluated based on readability and best practices, which you are encouraged to explain with code comments.

Tips

Including the Roman numerals for the special cases of 4, 9, 40, 90, 400 and 900 in your comparisons will make it much easier to correctly convert the values.

Solution

Submissions are closed.