Challenge #9 – Roman Numerals

31 August 2020 Closed Twig Intermediate

Giv­en a num­ber, cal­cu­late its cor­res­pond­ing Roman numer­al using a twig macro.

Chal­lenge

The chal­lenge is to write a macro that takes a num­ber as a para­met­er and out­puts the num­ber con­ver­ted to a Roman numer­al. For example:

4 => IV

61 => LXI

549 => DXLIX

Here is an algorithm that you can follow:

  1. Find the largest Roman numer­al that a giv­en num­ber is great­er or equal to.
  2. Out­put the Roman numer­al found and decre­ment its value from the giv­en number.
  3. Repeat the pro­cess until the num­ber 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, min­im­ise the num­ber of times that the algorithm must repeat the process.

Rules

The solu­tion should be writ­ten using nat­ive twig tags only, so you can use twig​fiddle​.com to work on and solve the chal­lenge. The code will be eval­u­ated based on read­ab­il­ity and best prac­tices, which you are encour­aged to explain with code comments.

Tips

Includ­ing the Roman numer­als for the spe­cial cases of 4, 9, 40, 90, 400 and 900 in your com­par­is­ons will make it much easi­er to cor­rectly con­vert the values.

Solution

Submissions are closed.