Skip to main content
11 of 11
edited tags
Wezl
  • 1.5k
  • 17
  • 46

Roman Numeral-like Code Generator

Background

Roman numeral is a simple number system with the following properties:

  • Each symbol in the system maps to a specific value. (e.g. I = 1, V = 5, X = 10, C = 100)
  • The value of a Roman numeral can be evaluated as follows:
    • First, find all occurrences of adjacent pairs of symbols where a strictly smaller-valued symbol comes first (e.g. IV, XC). Each such pair is evaluated as the backward difference of two values (e.g. IV = 5 - 1 = 4).
    • Then, interpret the remaining symbols as-is and sum all values in it.
      MMCMXCIV = M + M + CM + XC + IV
               = 1000 + 1000 + (1000 - 100) + (100 - 10) + (5 - 1)
               = 2994
      

Task

Your job is to write a function/program \$F\$ that takes a positive integer \$n\$ and generates a code fragment \$F(n)\$ (not necessarily in the same language). The outputted code fragments must have the following properties:

  • \$F(n)\$ as a full program must output the number \$n\$.
  • \$F(a)+\!\!\!+\,F(b)\$ as a program (where \$+\!\!+\$ means concatenation) must output \$a+b\$ if \$a≥b\$, \$b−a\$ otherwise.
  • This must extend to any number of code fragments emitted by your program in the way that \$b−a\$ cases take precedence (think of an arithmetic expression with +s and -s, but the two sides of -s are flipped and it has higher precedence than +).
    • You do not need to consider the cases where three consecutive input numbers are strictly increasing (the equivalent arithmetic expression has two consecutive -s).

Your score is the byte count of \$F\$. Shortest code in bytes wins.

Example

If \$F(10)\$ outputs the code fragment ABC, and \$F(3)\$ outputs the code fragment xyz:

  • The program ABC should output 10.
  • The program xyz should output 3.
  • The program ABCxyz should output 13.
  • The program xyzABC should output 7.
  • The program ABCABCABC should output 30.
  • The program ABCABCxyzxyzABCxyzxyzABC should output 40, since
    [10, 10, 3, 3, 10, 3, 3, 10] => 10 + 10 + 3 + (10-3) + 3 + (10-3) = 40
    

Additionally, if \$F(8)\$ outputs the code fragment ****:

  • The program ABC****xyz should output 10 + 8 + 3 = 21.
  • The program ****ABCxyz should output (10-8) + 3 = 5.
  • The program xyz********ABC should output (8-3) + (10-8) = 7.
  • You do not need to consider the program xyz****ABC, which contains three consecutive strictly increasing numbers (3, 8, 10).
Wezl
  • 1.5k
  • 17
  • 46