Is it possible to convert a number into Roman numerals using this method?

I am experimenting with creating my own method for Romanising numbers and I'm seeking some advice on its feasibility.

Currently, my code returns Null with each iteration. I can't figure out what's causing this issue. Any suggestions would be greatly appreciated!

var array;
var result = [];

function convertToRoman(num) {
  array = num.toString().split('').reverse();

  roman = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
    "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
    "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"
  ];

  for (i = 0, j = 0; i < array.length; i++, j += 10) {
    var location = array[i] + j;
    result = result.concat(roman[location]);
  }

  return result.reverse().join();
}

console.log(convertToRoman(123));

Answer №1

When dealing with an array that contains strings, it's important to remember to convert them back into integers for arithmetic operations. Here's one way you could approach this:

var roman = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
  "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
  "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"
];

function convertToRoman(num) {
  var result = [];
  var array = num.toString().split('').reverse();

  for (i = 0, j = 0; i < array.length; i++, j += 10) {
    var location = parseInt(array[i]) + j;
    result.push(roman[location]);
  }

  return result.reverse().join('');
}

console.log(convertToRoman(123));

It's worth noting that some changes were made in terms of variable scope and the use of array.push(). The code wasn't tested with multiple inputs, however, the primary focus was on getting the algorithm correct rather than optimizing it for all scenarios.

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

Using Three.js to Apply Textures

After creating a texture with canvas, I encountered a small issue. I am unable to turn my texture as shown in the image. Can anyone provide guidance on how to accomplish this? setTexture = (name, font = 20) => { const canvas = window.docu ...

Create a client-side script in asp.net for handling the default behavior of the

Currently working on a project in asp.net, and I am exploring options to dynamically change the target of the ENTER key press on the client side. The goal is to determine the target based on the currently focused div or input element. The desired targets ...

Is it possible to fill an array of strings using a for loop?

Looking to use a for loop to populate an array of strings and then print them out. string R_name[3] = {""}; for(int i=0; i<=2; i++){ R_name[i] = 'Small'; cout<<R_name[j]<<" "<< endl; } Encounteri ...

The Date Picker pops up automatically upon opening the page but this feature is only available on IE10

There seems to be an issue with the date picker opening automatically on IE10, while it works fine in Firefox where it only appears when you click on the associated text box. Does anyone have insight into why this might be happening specifically in IE10? ...

Subscription date is activated when a different part of the state changes in ngrx

Within my state, I have properties named start and end which store dates. Whenever any other part of the state is modified, the subscription for these start and end dates is triggered. Here is the subscription implementation: this.subs.sink = this.store ...

Instructions for adding an onfocus event listener to an input field in order to dynamically change the formatting of associated labels

I'm looking to change the style of my input labels to a more fancy look by implementing the .fancyclass style when using the onfocus event on the input field. I am curious to know how this can be achieved through event listeners in Javascript? ...

Exploring the document object model, identifying the most frequently occurring text, and applying a class to the element's parent

I have been navigating through this HTML structure: <ul> <li class="item"> <span class="category"> most frequent text </span> </li> <li class="item"> ...

Dynamic styles object for React components with inline styles

I have a styles object let styles = { step_div:{ height:'150px', } } I'm trying to display multiple div elements with different colors using React class Layout extends React.Component{ constructor(props) { super(props); ...

Updating a nested array in MongoDB using key-value pairs

Is there a way to efficiently update a nested array by the key value in a list? { "_id": "mainId", "events": [{ "id": 1, "profile": 10, } { "id" ...

Enhancing your Selenium test case strategies for better performance

I've created a test case that compares two arrays, removing matching elements and throwing an exception for non-matching ones. Although it's functional, the test is quite long and messy. Can anyone suggest ways to optimize or improve it? System ...

The occurrence of duplicated items within Kaminari would be worthy of

In my controller, I am working with an array of objects that are paginated using Kaminari: @pics = Pic.page(params[:page]).per(12).order(sort_column) To create a manual infinite scroll effect on the same page, I use AJAX to render each new set of 12 pics ...

How to use React MUI Checkbox to set the checked value as false

I'm encountering an issue with the React MUI - Checkbox component. On my site, I have a checkbox linked to a handler that targets a REST API endpoint. This endpoint sets a boolean flag for the user in the database on a POST request and returns the boo ...

Enhance Your Contact Form with jQuery Validation Engine

I have implemented a contact form with added features of jQuery fadeLabel and validationEngine to enhance its appearance on the page. The file containing this code is either index.php or .html, which I have not yet determined. Here is the script from my i ...

Why is a question mark added to the URL when the login button is clicked

I've encountered an issue where clicking this code for the first time redirects me to localhost:8080//? instead of localhost:8080//admin.html. Any idea why this is happening? $("#admin-login").click(function(){ var data = {"username": $("#admin ...

Discover the power of positioning data labels in c3js!

Is there a way to adjust the position of labels above the data in a c3 bar chart? The official documentation explains how to modify the positions of labels on the x and y measurement axes by manipulating integers for y and x, but I couldn't find any i ...

Obtain the current time and date in India

I'm trying to retrieve the current time and date in Indian Standard Time, and I attempted the following code: let today = new Date(); let indianTime = today.toLocaleString("en-US", "Asia/Delhi"); It displays: "Mon Jul 26 2021 ...

What could be causing the state to not update as anticipated?

I am currently in the process of developing a TicTacToe game and have a requirement to maintain the current player in state under the name currentPlayer. The idea is that after one player makes a move, I need to update currentPlayer to represent the opposi ...

Choose values from an array to act as foreign keys to join multiple tables

In the table depicted below table CREATE TABLE IF NOT EXISTS "Article"( "ArticleId" SERIAL NOT NULL, "GenresIdList" integer[], ... PRIMARY KEY ("ArticleId") ); CREATE TABLE IF NOT EXISTS "Tag0"( "TagId" SERIAL NOT NULL, "Name" varchar, ... PRIMARY K ...

Utilizing JSON information to apply style formatting using jQuery

Something strange is happening with the code below: function loadTextbox(jsonUrl,divId){ $.getJSON(jsonUrl, function(json) { $('#' + divId).html('<h2>'+json.heading+'</h2>'); alert(json.config. ...

Harvesting TypeScript attributes

I am encountering an issue with my form handling method. I have the following interface and useState in place: interface Message { message?: { title?: string; description?: string; body?: string; }; } const [message, setMessage] = useState ...