Nerd For Tech
Published in

Nerd For Tech

Write Up Code Wars — Roman Numerals Encoder Solutions JavaScript

Code Wars is best platform for learning algorithm from programming language, here I want to write the solution for ‘Roman Numerals Encoder’ challenge using JavaScript. When it was written, the challenge is still in kyu 6.

Question

Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.

Example

solution(1000); // should return 'M'

Hints

Symbol    Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Remember that there can't be more than 3 identical symbols in a row.

As you can see, the challenge purpose is to make every integer we input become roman symbol. If you still remember in with first algorithm you take. For me, it was assigning quiz value into word A,B,C,D, or E. It just all the same, the different is that this challenge we need to assign it into roman encoder. So it look like hard right?.

So, you can finish it using the old way, like this (This idea from Phares)

It’s too long right? From the old way, we can improve it. As you can see, every roman character will turn into specific number. So, by declaring it as an object, we can get the answer. Here is my answer that improved from another solution that I found in google.

In the line 11, I used repeat function. This is an inbuilt function that used for build new string that contains the specified number of copies of the string. For the example I declared new variable word, and repeating it three times.

The word will be repeated right? In my solution, I just put it into the for loop function, so it will repeated until the number finished.

Yeah, exactly I still newbie here and there so much things I don’t know yet. I hope this article can help you and eager you to never stop learning.

Have a Nice Code 😉

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store