lundi 29 août 2016

Converting to Roman Numerals in Javascript - Weird bug

function convertToRoman(num) {

  var thisMap = {

  1:[1],
  2:[1, 1],
  3:[1, 1, 1],
  4:[1, 5],
  5:[5],
  6:[5, 1],
  7:[5, 1, 1],
  8:[5, 1, 1, 1],
  9:[1, 10],
  0:[0]

  };

  var numMap = {

  1000:"M",
  500:"D",
  100:"C",
  50:"L",
  10:"X",
  5:"V",
  1:"I"

  };

  numArr = num.toString().split("");

  var thisIndex = 1;

  var tallyArr = [];

  for (var i = numArr.length - 1; i >= 0; i--) {

   tallyArr.unshift(thisMap[numArr[i]]);

  }

  thisIndex = Math.pow(10, tallyArr.length - 1);

  checkArr = [];

  <<<BUG HERE>>> 

  for (var x = 0; x < tallyArr.length; x++) {

    for (var y = 0; y < tallyArr[x].length; y++) {

      tallyArr[x][y] *= thisIndex;

    }

    thisIndex = thisIndex / 10;

  }

  <<</BUG HERE>>>

  var finalArr = [];

  for (var a = 0; a < tallyArr.length; a++) {

    for (var b = 0; b < tallyArr[a].length; b++) {

      finalArr.push(numMap[tallyArr[a][b]]);

    }

  }

  finalAnswer = finalArr.join("");

  return finalAnswer;

}

convertToRoman(88);

So this is my function for converting a number into a Roman Numeral in Javascript. It basically formats every number into the right format using thisMap, then uses thisIndex to multiply by either 1000, 100 or 10, and then compares to numMap to get the correct Roman Numeral.

It seems to work in most of the test cases, except with 44, 99, or 3999.

In these cases, it seems to multiply the numbers by the wrong amount, so 44 becomes XLXL, when it should be XLIV.

I think the bug is between the <<>> tags I've inserted, because that is where the numbers seem to be multiplied wrong.

However, I can't spot the problem.

Thanks.




Aucun commentaire:

Enregistrer un commentaire