Search code examples
javascriptconvertersroman-numerals

Converting roman numbers in arabic numbers -- recursiv


i´m new to JavaScript and learning with the Help of the Website https://www.jshero.net/koans/roman1.html.

The exercise is to code a converter, that converts roman numbers from a string 'CDLXXXIII' to the arabic number.

I made a code with a "while loop" that works, but the website wants me to do it with a recursive function.

Heres my code:

function roman(roemische){
  let romBuchstaben = ['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM', 'M'];
  let romZahlen = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000];
  let summe = 0;
  while (roemische.length > 0){
    let suchzeichen = roemische[0] + roemische[1];
    if (romBuchstaben.indexOf(suchzeichen) !== -1){
      summe += romZahlen[romBuchstaben.indexOf(suchzeichen)];
      roemische = roemische.substr(2,roemische.length-2);
    } else {
    summe += romZahlen[romBuchstaben.indexOf(roemische[0])];
    roemische = roemische.substr(1, roemische.length-1);

  }

  }
  return summe;
  }

(I´m sorry that the var's are in german).

I´m not that familiar with recursion, could some1 give me an example, how to do it with one?

Greetings Marcel


Solution

  • You could change the storage of the values a bit by taking an object with roman signs as keys and decimal values.

    For crating a recursive function, you could add an exit condition which is here just a check for an empty string and return zero in this case.

    Then check if two character are in the object and if so take the value and add the result of calling the function again with the rest of the string.

    If not take only the first character and the value and call the function again for getting the rest of the string.

    function roman(number) {
        const
            values = { 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 },
            two = number.slice(0, 2);
    
        if (!number) return 0;
        return two in values
            ? values[two] + roman(number.slice(2))
            : values[number[0]] + roman(number.slice(1));
    }
    
    console.log(roman('CDLXXXIII')); // 483