Convert Roman Numerals with freecodecamp programming site

Why is it that the initial code snippet, which uses decimal numbers as keys and Roman numerals as values, fails the input-output test on freecodecamp.com for converting decimal numbers to Roman numerals? Conversely, the alternate code snippet, where the keys and values are interchanged, successfully passes the test. The only distinction between the two versions lies in the arrangement of keys and values within the romanNumerals object.

What is the reason behind this seemingly minor alteration impacting the test outcomes?

The initial code designed to convert decimal numbers to Roman numerals functions correctly solely for inputs like convertToRoman(2) and convertToRoman(3), but encounters failures with other input values such as 4, 5, 9, 12, 16, and so forth. Despite an apparently sound logic and loop iterations, it generates incorrect outputs for a range of input values.

What could be the root cause behind this specific issue occurring for the mentioned input values, and how might it be rectified?

1.

function convertToRoman(num) {
  const romanNumerals = {
    1000: "M",
    900: "CM",
    500: "D",
    400: "CD",
    100: "C",
    90: "XC",
    50: "L",
    40: "XL",
    10: "X",
    9: "IX",
    5: "V",
    4: "IV",
    1: "I"
  };

  let roman = "";
  let restartLoop = false;

  do {
    restartLoop = false;

    for (let key in romanNumerals) {
      if (num >= key) {
        roman += romanNumerals[key];
        num -= key;
        restartLoop = true;
        break;
      }
    }
  } while (restartLoop);

  return roman;
}

console.log(convertToRoman(3))
console.log(convertToRoman(4))
console.log(convertToRoman(23))

2.

function convertToRoman(num) {
  const romanNumerals = {
    "M": 1000,
    "CM": 900,
    "D": 500,
    "CD": 400,
    "C": 100,
    "XC": 90,
    "L": 50,
    "XL": 40,
    "X": 10,
    "IX": 9,
    "V": 5,
    "IV": 4,
    "I": 1
  };

  let roman = "";
  let restartLoop = false;

  do {
    restartLoop = false;

    for (let key in romanNumerals) {
      if (num >= romanNumerals[key]) {
        roman += key;
        num -= romanNumerals[key];
        restartLoop = true;
        break;
      }
    }
  } while (restartLoop);

  return roman;
}

console.log(convertToRoman(3))
console.log(convertToRoman(4))
console.log(convertToRoman(23))

Answer №1

When assigning values to numeral keys, looping through them will return them sorted. This is specified in the following excerpt:

The order of traversal, according to the latest ECMAScript specification, is well-defined and consistent across all implementations. When traversing through each component of the prototype chain, non-negative integer keys (those that can be array indices) will be iterated over first in ascending order by value, followed by other string keys in ascending chronological order of property creation. source

const highToLow = {
  5: 'five',
  4: 'four',
  3: 'three'
}

console.log(highToLow);

In essence, by adding values to your object in reverse order, you will see that number 1 (the I) appears first.

I recommend sticking with the second example of your code, as it will consistently work regardless of the values added to the object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The orbitController in threejs is malfunctioning and failing to properly adjust the camera's LookAt

Currently, I am working on a project using three.js. In this project, I have implemented OrbitControls for my camera. However, there are situations where I need to manually adjust the rotation of the camera. The challenge I am facing is that when I try t ...

Error: Unable to locate image module in REACT

Trying to troubleshoot image loading in a React project. Currently testing with an individual image, but plan to eventually store multiple images in an array for easier management. However, I'm encountering an issue where the image won't load and ...

Is there a way to verify the existence of an EJS variable?

When working with my Node.js application, I encountered an issue with EJS layout where if the required data is not available in the EJS file, it throws an error. I am looking for a way to add a condition to check for the availability of the EJS variable in ...

Set up local npm packages for easy access by different projects

Can someone explain to me how npm works compared to Maven (I have a background in Java) when it comes to package management? I've developed a generic component using Angular 4 that will be used across multiple projects. I've published it to our n ...

The web method within the aspx page is failing to execute

On page load, I am attempting to make an ajax request using the AngularJS $http service to fetch JSON data from a web method located in my User.aspx.cs page. The web method is defined as follows: [WebMethod] [ScriptMethod(ResponseFormat=ResponseForma ...

Add a new value to an object and ensure that only the unique value is appended to the first

I have a scenario where I have 2 objects, and I need to add a new key value pair to only the first matching object of its kind. Obj1 [{ buyDate: "yesterday", productId: "0001", consumerId: "John", price: 10 // add new key valu ...

The deletion feature on my virtual keyboard was malfunctioning when using JavaScript

The virtual keyboard feature I added to my website isn't working properly, specifically the delete function. How can I fix this issue? Below is my code: HTML Code <input type="text" maxlength="12" min="10" name="msidn" id="jkeyboard" min="1" sty ...

PhantomJS Alert: UnresolvedPromiseRejectionNotice

My main objective is to extract data from a website using Node.js. I have successfully managed to gather information using the request package, however, the website I am targeting contains dynamic content which cannot be accessed solely with request. Aft ...

Utilizing the $scope variable within an event in the Google Maps API

I am having an issue using $scope within this function. Where should I define the argument $scope so that it works properly? Thank you Below is the basic structure of my code with key lines included: myApp.controller('myCtrl', ['$scope&ap ...

Automatically navigate to the bottom of the page by applying the overflow auto feature

I've been working on a chat application using Vue.js. I have set the overflow property to auto for my div element. My goal is to automatically scroll to the bottom of the div so that users won't have to manually click the scrollbar to view the la ...

The issue arises when using multiple route files in Route.js, as it hinders the ability to incorporate additional functions within the

After breaking down Route.js into multiple controllers, I'm stuck on why I can't add an extra function to block permissions for viewing the page. // route.js module.exports = function(app, passport) { app.use('/profile&apos ...

In a perplexing twist, requests made to the Express app arrive with empty bodies despite data being sent, but this anomaly occurs

Welcome to the community of inquisitive individuals on Stack! I'm facing an interesting challenge while developing an Express app. Despite everything running smoothly with two routes, I've hit a roadblock with one route that seems to have empty i ...

Tips for troubleshooting and resolving the npm ERR! code E404 issue in Vue.js when implementing a datepicker

I am a newcomer to Vue.js and I am currently exploring the use of a datepicker from However, upon importing the script for usage, I encountered the following message: 'VMdDateRangePicker' is declared but its value is never read.ts(6133) Cou ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

Executing Rake tasks on the live server fails because of an issue with ExecJS

I currently have a Rails 4 application running on a RHEL 6 server. The production environment utilizes Passenger and Apache2. Recently, I've been attempting to schedule Rake tasks in the production environment using the Whenever Gem and Cron. Howev ...

The issue with loading scripts in a ReactJS NextJS app is related to the inline condition not working

I'm having trouble with an inline condition for loading scripts. The condition seems to be working because the tag is displaying text, but when it comes to scripts, it doesn't work. How can I resolve this issue? const cookie = new Cookies().get ...

Sliding out list elements with jQuery ladder effect

I'm stuck on a seemingly simple task and need some guidance. facepalm. Currently, my site at this link has a menu list item issue where they all come out from the left side after the picture loads. I want them to slide out one by one, starting from t ...

Determining the position and offset of an element

Currently, I am facing a dilemma with my table of images. I want to add an icon to the corner of each image so that they align perfectly. I attempted to achieve this using relative CSS positioning, but it resulted in the icons extending beyond the cells an ...

An error occurred while processing the JSReport request

I am encountering an issue while trying to utilize the jsreport API for rendering a report template. The error I am facing is as follows: { body: "{"body":"\"{\\\"template\\\":{\\\"shortid\\& ...

What is the best way to say hello using jQuery?

I need some assistance with a task that involves entering my name into an input field, clicking a button, and having an h1 tag display below the input saying Hello (my name)! Unfortunately, I am struggling to figure out how to achieve this. Below is the H ...