// you’re reading...
1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 5.00 out of 5)
Loading...

Project Euler Solutions

Project Euler 89 Solution

Project Euler 89 Solution

Project Euler 89: Calculate characters saved by expressing Roman numerals in minimal form


Problem Description

The rules for writing Roman numerals allow for many ways of writing each number (see FAQ: Roman Numerals). However, there is always a “best” way of writing a particular number.

For example, the following represent all of the legitimate ways of writing the number sixteen:

IIIIIIIIIIIIIIII
VIIIIIIIIIII
VVIIIIII
XIIIIII
VVVI
XVI

The last example being considered the most efficient, as it uses the least number of numerals.

The 11K text file, roman.txt (right click and ‘Save Link/Target As…’), contains one thousand numbers written in valid, but not necessarily minimal, Roman numerals; that is, they are arranged in descending units and obey the subtractive pair rule (see FAQ for the definitive rules for this problem).

Find the number of characters saved by writing each of these in their minimal form.

Note: You can assume that all the Roman numerals in the file contain no more than four consecutive identical units.

Analysis

A good example for using regular expressions. Coded as simple string replacement to determine the number of characters saved. Here’s the table of replacements in order of execution and the resulting savings in characters:
DCCCC to CM, LXXXX to XC and VIIII to IX saves 3 characters.
IIII to IV, XXXX to XL and CCCC to CD saves 2 characters.

In all cases we are replacing 4 or 5 character length strings with just 2 character length strings, so, we just need to know the difference in lengths before and after the replacement to calculate the numbers of characters saved. We are not concerned with a real translation, just space saved; the replacement is just arbitrarily two spaces.

Project Euler 89 Solution

Runs < 0.001 seconds in Python 2.7.

download arrowUse this link to get the Project Euler 89 Solution Python 2.7 source.

Comments

  • Here’s a copy of the text file: roman.txt used as input.
  • I think I read from an external source differently every time I code a solution. It might be an idea to write a magic function that just gets the data into an array and somehow knows what to do. Even looks for a backup file if the one specified is unavailable. Wait, I’m much too lazy to do that – never mind.
Project Euler 89 Solution last updated

Discussion

No comments yet.

Post a comment