2

Trying to print out the specific value from the following Map

Map strokes = [1000:['M','?','?'],
               100:['C','D','M'],
               10:['X','L','C'],
               1:['I','V','X']]

In other words, if I have a value of 1234 I want it based on a switch statement print out in Roman Numeral format. Which means I want the value of M to print out and C and C and X and X and X and I and V which would then put everything together into the value of MCCXXXIV.

So far at this point, I am trying to print out the first Character from the Key List of 1000.

I am only able to get the entire values from the Key List 1000

Output ['M','?','?']

tkruse
  • 10,222
  • 7
  • 53
  • 80
  • Hi lionWolf0517, welcome to Stack Overflow. Can you let us know how you are printing the values of the map, maybe by posting a few lines of code? – Kevin Chen Apr 13 '19 at 20:31
  • Sure So far it is being displayed as such. println strokes.get(1000) – lionWolf0517 Apr 14 '19 at 01:08
  • But 4 is IV, not IIII. How do you cover that case? – Rcordoval Apr 14 '19 at 23:35
  • Please add the code, with what you have tried to the question itself. And add the error or the unexpected behaviour so we can improve on it. – cfrick Apr 15 '19 at 08:41
  • `strokes[1000][0]` will print the first value. You could consider writing a loop that extracts each digit, and for each digit use a switch statement like `switch(digit) { case 1: return strokes[index][0];case 2: return strokes[index][0] + strokes[index][0] ...};` – tkruse Apr 21 '19 at 01:47

1 Answers1

0

You could convert everything "as is" and then replace border cases like:

  • IIII should be IV
  • IIIII should be V
  • XXXXX should be L
  • And so on..

I scripted a converter using a Map:

strokes = [M:1000, C:100, X:10, I:1]
int number = 5555;
int numSize = String.valueOf(number).length();
String roman = ""

 strokes.each { stroke ->
    while ( number >= stroke.value ) {
        number -= stroke.value
        roman += stroke.key
    }
 }
 println "raw: " + roman
 println toRoman(roman)

 private static String toRoman(String number) {
        return number
                .replace("IIIII", "V")
                .replace("IIII", "IV")
                .replace("VV", "X")
                .replace("VIV", "IX")
                .replace("XXXXX", "L")
                .replace("XXXX", "XL")
                .replace("LL", "C")
                .replace("LXL", "XC")
                .replace("CCCCC", "D")
                .replace("CCCC", "CD")
                .replace("DD", "M")
                .replace("DCD", "CM");
}

Examples:

5555:

raw: MMMMMCCCCCXXXXXIIIII
MMMMMDLV

1234:

raw: MCCXXXIIII
MCCXXXIV
Rcordoval
  • 1,932
  • 2
  • 19
  • 25