Given a number, calculate its corresponding Roman numeral using a twig macro.
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:
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.
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.
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.
Submissions are closed.