0

I want to implement Algorithm which converts Roman numeral to Arabic with Javascript. Using the following suggested methods.

  1. Array.prototype.splice()
  2. Array.prototype.indexOf()
  3. Array.prototype.join()

I have already found the algorithm which solves this task

function convertToRoman(num) {

  var numeric = [ 5000,4000,1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ];
  var roman = [ 'V\u0305','I\u0305V\u0305','M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I' ];

  var output = '', i, len = numeric.length;

  for (i = 0; i < len; i++) {
    while (numeric[i] <= num) {
      output += roman[i];
      num -= numeric[i];
    }
  }

  return output;
}

convertToRoman(4999);

Nevertheless i'm curious how to implement an algorithm with above mentioned methods.

Thanks, please do not judge me harshly, i'm a beginner programmer.

NZMAI
  • 536
  • 5
  • 27
  • Why do you explicitly want to use these functions when your current solution seems fine (probably better than shoehorning some non-related functions into it)? Is this homework? – str Jul 30 '16 at 07:10
  • Because i want to understand how to apply these methods. No it is not a home work it is an algorithm from Free Code Camp. – NZMAI Jul 30 '16 at 07:16

1 Answers1

1

I think the question has already been answered:
https://stackoverflow.com/a/9083857/4269495

Number to Roman Numeral:

Number.prototype.toRoman= function () {
    var num = Math.floor(this), 
        val, s= '', i= 0, 
        v = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1], 
        r = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']; 

    function toBigRoman(n) {
        var ret = '', n1 = '', rem = n;
        while (rem > 1000) {
            var prefix = '', suffix = '', n = rem, s = '' + rem, magnitude = 1;
            while (n > 1000) {
                n /= 1000;
                magnitude *= 1000;
                prefix += '(';
                suffix += ')';
            }
            n1 = Math.floor(n);
            rem = s - (n1 * magnitude);
            ret += prefix + n1.toRoman() + suffix;
        }
        return ret + rem.toRoman();
    }

    if (this - num || num < 1) num = 0;
    if (num > 3999) return toBigRoman(num);

    while (num) {
        val = v[i];
        while (num >= val) {
            num -= val;
            s += r[i];
        }
        ++i;
    }
    return s;
};
Community
  • 1
  • 1