Programming Problems & Solutions : “Conquering Roman Numerals in C#: An Exercise in Classical Coding”. The introduction to this series is here and includes all links to every post in the series. If you’d like to watch the video (see just below this), or the AI code up (it’s at the bottom of the post) they’re available! But if you just want to work through the problem keep reading, I cover most of what is in the video plus a slightly different path down below.
The continuation with CoPilot AI Tooling is at the end of the post.
The Challenge: Translating Numbers into a Language of Antiquity
Today, I’ll dive into a fascinating challenge: converting modern numbers into their ancient Roman numeral counterparts. The task is straightforward but intricate, involving a programming challenge that takes any positive integer from 1 to 3999 and converts it into the corresponding Roman numeral.
To convert regular decimal numbers into Roman numerals, one must follow a set of rules based on the values and combinations of specific Roman numeral characters. Here’s a brief summary of the conversion process:
Programming Problems & Solutions : “How to Format Arrays as Phone Numbers with NUnit Testing”. The introduction to this series is here and includes all links to every post in the series. If you’d like to watch the video (see just below this), or the AI code up (it’s at the bottom of the post) they’re available! But if you just want to work through the problem keep reading, I cover most of what is in the video plus a slightly different path down below.
The AI continuation and lagniappe is at the bottom of this post.
In the world of software development, sometimes a seemingly simple task has lessons to teach such as language features and problem-solving. Today, I’m diving into a fun coding challenge that does exactly that: writing a method in C# that takes an array of 10 integers and returns these numbers formatted as a phone number. This exercise is perfect for understanding array manipulation, string formatting, and how to effectively use testing frameworks like NUnit to verify our solution.
Programming Problems & Solutions: “Finding the Maximum Sum Path in a Binary Tree” is the first in this series. The introduction to this series is here and includes all links to every post in the series. If you’d like to watch the video (see just below this), or the AI code up (it’s at the bottom of the post) they’re available! But if you just want to work through the problem keep reading, I cover most of what is in the video plus a slightly different path down below.
Scroll to the bottom to see the AI work through of the code base.
Doing a little dive into the world of binary trees. If you’re in college, just got out, or having flashbacks to algorithms and data structures classes, this will be familiar territory. It’s been a hot minute since I’ve toiled through these, so figured it’d be fun to dive in again for some more modern purpose. I’m going to – over the course of the next few weeks – work through a number of algorithm and data structures problems, puzzles, katas, or what have you – and then once complete work through them with various AI tools. I’ll measure the results in whatever ways seem to bring good defining characteristics of the system and post the results. So join me, on this journey into algorithms, data structures, and a dose of AI (actually LLMs and ML but…) systems and services.
# Project Scaffold Init Script
# Please answer a few questions and we will generate
# two files:
#
# build.fsx This will be your build script
# docs/tools/generate.fsx This script will generate your
# documentation
#
# NOTE: Aside from the Project Name, you may leave any
# of these blank, but you will need to change the defaults
# in the generated scripts.
#
Project Name (used for solution/project files): sharpKataStringCalc
Summary (a short description): A code kata for the string calculator exercise.
Description (longer description used by NuGet): The code kata, kicked off my Roy Osherove, this is my iteration of it (at least my first iteration of it).
Author: Adron Hall
Tags (separated by spaces): fsharp f# code kata stringcalculator
Github User or Organization: adron
Github Project Name (leave blank to use Project Name):
[/sourcecode]
Once I hit enter after entering the information I’ve gotten more than a few of these broken builds.
[sourcecode language=”bash”]
Time Elapsed 00:00:00.1609190
Running build failed.
Error:
Building /Users/adronhall/Coderz/sharpKataStringCalc/sharpKataStringCalc.sln failed with exitcode 1.
———————————————————————
Build Time Report
———————————————————————
Target Duration
—— ——–
Clean 00:00:00.0019508
AssemblyInfo 00:00:00.0107624
Total: 00:00:00.6460652
Status: Failure
———————————————————————
1) Building /Users/adronhall/Coderz/sharpKataStringCalc/sharpKataStringCalc.sln failed with exitcode 1.
2) : /Users/adronhall/Coderz/sharpKataStringCalc/src/sharpKataStringCalc/sharpKataStringCalc.fsproj(0,0): Target named ‘Rebuild’ not found in the project.
3) : /Users/adronhall/Coderz/sharpKataStringCalc/tests/sharpKataStringCalc.Tests/sharpKataStringCalc.Tests.fsproj(0,0): /Users/adronhall/Coderz/sharpKataStringCalc/tests/sharpKataStringCalc.Tests/sharpKataStringCalc.Tests.fsproj: The required attribute "Project" in Import is empty
———————————————————————
[/sourcecode]
This problem I was able to solve once, based on what I did in a previous blog entry “That Non-Windows Scaffolding for OS-X and Linux |> I Broke It! But…“. Which seemed odd that I fixed it previously. To help with the build I actually opened it up in Xamarin Studio. Now, one of the problems with doing this, is that it’s only available on Windows & OS-X. I’m however interested in using this stuff on Linux too, but that’s looking a bit more difficult the more I work with the toolchain unfortunately.
After working through the issue I found that on one OS-X box I’d installed Mono via make and F# via make and that messes things up. Do one or the other and you should be ok. So on my other two OS-X boxes (I’ve a personal retina and a work retina) the build worked flawlessly, and when it works flawlessly it looks like this toward the end of the build execution.
I’ve gotten this to work on OS-X and Windows just fine using the straight up ProjectScaffold and the ./build.sh. So all is good, I’m going to move forward with writing the kata based on that and loop back around to straighten out the Linux issues.
To run the tests, execute the following script after creating the project scaffold.
First off, what are the ideas behind the string calculator kata? Well here’s how Roy Osherove lays it out this particular code kata.
Before you start:
Try not to read ahead.
Do one task at a time. The trick is to learn to work incrementally.
Make sure you only test for correct inputs. there is no need to test for invalid inputs for this kata.
String Calculator
Create a simple String calculator with a method int Add(string numbers)
The method can take 0, 1 or 2 numbers, and will return their sum (for an empty string it will return 0) for example “” or “1” or “1 2”
Start with the simplest test case of an empty string and move to 1 and two numbers
Remember to solve things as simply as possible so that you force yourself to write tests you did not think about
Remember to refactor after each passing test
Allow the Add method to handle an unknown amount of numbers.
Allow the Add method to handle new lines between numbers (instead of an empty space).
the following input is ok: “1\n2 3” (will equal 6)
the following input is NOT ok: “1 \n” (not need to prove it – just clarifying)
Support different delimiters
to change a delimiter, the beginning of the string will contain a separate line that looks like this: “//[delimiter]\n[numbers…]” for example “//;\n1;2” should return three where the default delimiter is ‘;’ .
the first line is optional. all existing scenarios should still be supported
Calling Add with a negative number will throw an exception “negatives not allowed” – and the negative that was passed.if there are multiple negatives, show all of them in the exception message
Numbers bigger than 1000 should be ignored, so adding 2 + 1001 = 2
Delimiters can be of any length with the following format: “//[delimiter]\n” for example: “//[***]\n1***2***3” should return 6
Allow multiple delimiters like this: “//[delim1][delim2]\n” for example “//[*][%]\n1*2%3” should return 6.
Make sure you can also handle multiple delimiters with length longer than one char.
Ok, so now that we’re clear on the string calculator, I’m going to dig into knocking out the first item, “Create a simple string calculator with a method int Add (string numbers)”
But first, in TDD fashion let’s write the test and make it fail first. I changed the code in the Tests.fs file in the tests directory and tests project to read as follows.
open System
open sharpKataStringCalc
open NUnit.Framework
[<TestFixture>]
type CalculatorTests() =
[<Test>]
member x.add_empty_string() =
let calculator = Calculator()
let result = calculator.Add ""
Assert.That(result, Is.EqualTo 0)
[/sourcecode]
That gets us a failing test, since we don’t even have any implementation yet. So now I’ll add the first part of the implementation code. First I created a Calculator.fs file and deleted the other file that ProjectScaffold put in there in the first place.
type Calculator() =
member x.Add express =
0
[/sourcecode]
Ok, that gives me a passing test for the first phase of all this. Now since I’m a total F# newb still I’ve got to kind of dig around and read documentation while I’m working through this. So I’m taking a couple of hours while Roy’s suggestion is to use 30 minutes to do this kata. But I figured it is a good way to force myself to learn the syntax and start getting into an F# refactoring practice.
The first thing I started to do was write a test where I set the Calculator() again that looked something like this. I didn’t like that so I tried to pull it out of the test.
[sourcecode language=”fsharp”]
[<TestCase("1", Result = 1)>]
member x.Add_single_number_returns_that_number expression =
let calculator = Calculator()
calculator.Add expression
[/sourcecode]
I ended up with something like this then.
[sourcecode language=”fsharp”]
let calculator = Calculator()
[<TestFixture>]
type CalculatorTests() =
[<Test>]
member x.add_empty_string() =
let result = calculator.Add ""
Assert.That(result, Is.EqualTo 0)
[<TestCase("1", Result = 1)>]
member x.Add_single_number_returns_that_number expression =
calculator.Add expression
[/sourcecode]
After adding that code with that little refactor I ran it, red light fail, so I then moved on to implementation for this test.
[sourcecode language=”fsharp”]
type Calculator() =
member x.Add expression =
match expression with
| "" -> 0
| _ -> 1
[/sourcecode]
Everything passed. So now on to the next scenario other subsequent number strings. I add another test and result condition.
[sourcecode language=”fsharp”]
[<TestCase("1", Result = 1)>]
[<TestCase("2", Result = 2)>]
member x.Add_single_number_returns_that_number expression =
calculator.Add expression
[/sourcecode]
It runs, gets a red light fail, I then implement with this minor addition.
[sourcecode language=”fsharp”]
type Calculator() =
member x.Add expression =
match expression with
| "" -> 0
| _ -> Int32.Parse expression
[/sourcecode]
Before moving on, I’m just going to cover some of the syntax I’ve been using. The | delimits individual matches, individual discriminated union cases, and enumeration values. In this particular case I’m just using it to match the empty string or the
wildcard. Which speaking of, the _ is a wildcard match or specifies a generic parameter. To learn more about these in detail check out match expressions or generics. There are lots of good things in there.
The other syntax is somewhat more self-explanatory so I’m going to leave it as is for the moment. It is, in the end, when executing the tests evident what is going on at least. Alright, back to the kata. Let’s actually add two numbers. For the test I’m just going to add another TestCase with two actual numbers.
[sourcecode language=”fsharp”]
[<TestCase("1", Result = 1)>]
[<TestCase("2", Result = 2)>]
[<TestCase("1 2", Result = 3)>]
member x.Add_single_number_returns_that_number expression =
calculator.Add expression
[/sourcecode]
Fails, so on to implementation. I’m just going to do this the cheap “it works” way and do something dumb.
[sourcecode language=”fsharp”]
type Calculator() =
member x.Add expression =
match expression with
| "" -> 0
| _ when expression.Contains " " -> 3
| _ -> Int32.Parse expression
[/sourcecode]
That’ll give me a passing green light, but I’ll add another bit of attribute to the test and get another failing test.
[sourcecode language=”fsharp”]
[<TestCase("1", Result = 1)>]
[<TestCase("2", Result = 2)>]
[<TestCase("1 2", Result = 3)>]
[<TestCase("2 3", Result = 5)>]
member x.Add_single_number_returns_that_number expression =
calculator.Add expression
[/sourcecode]
I’ll add the following code to implement and get a passing test.
[sourcecode language=”fsharp”]
type Calculator() =
member x.Add expression =
match expression with
| "" -> 0
| _ when expression.Contains " " ->
let numbers = expression.Split [| ‘ ‘ |]
(Int32.Parse numbers.[0]) + (Int32.Parse numbers.[1])
| _ -> Int32.Parse expression
[/sourcecode]
Ok. So that part of the match looks for an empty space, and then takes the two numbers opposite sides of that empty space (array item 0 and 1) and then parses them and adds them together. Keep in mind that ‘ ‘ signifies a single character, and not a string, even though for the contains method that executes on a string, passing in a string with ” ” is ok and the appropriate actions are taken by the compiler.
For the tests I’m going to do a refactor and break them apart just a bit and rename them using the “ xyz “ technique of methods. After the refactor the code looked like this. I got this idea from the “Use F# to write unit tests with readable names” tip.
[sourcecode language=”fsharp”]
[<TestFixture>]
type CalculatorTests() =
[<Test>]
member x.“should return zero if no string value is passed in.“() =
let result = calculator.Add ""
Assert.That(result, Is.EqualTo 0)
[<TestCase("1", Result = 1)>]
[<TestCase("2", Result = 2)>]
member x.“take one number and return that number“ expression =
calculator.Add expression
[<TestCase("1 2", Result = 3)>]
[<TestCase("2 3", Result = 5)>]
member x.“add single number to single number and return sum“ expression =
calculator.Add expression
[/sourcecode]
At this point I’m going to take a break, and wrap this up in a subsequent part of this series. It’s been a fun troubleshooting and getting started string calculator kata. So stay tuned and I’ll be slinging some F# math at ya real soon.
BEWARE, this is a crazy long post. So before you jump in for a read, just know that it isn’t a two minute read. 😉
A few days ago, my friend Aeden Jameson (@daliful) asks, “you want to work through a code kata this weekend?” I thought, well yeah, that’d be cool. So we met at Cafe Fiore and hacked out the beginning of a Kata based on the Roman to Arabic and Arabic to Roman Numerals. It was fun, which led me to working up an actual blog entry related to our kata session. This however, is just me working through a similar aspect of the numeral conversions with JavaScript. Enjoy.
First things first, I’m using QUnit which is available on Github with documentation on the jQuery Site. So if you’re going to work through these, go get that first. Or use another unit testing framework. I also am using Webstorm, which is a pretty sweet IDE for editing HTML, CSS, and JavaScript available from Jetbrains. You can even do scary stuff like edit and write PHP! Oh yeah that’s right! It IS absolutely worth the money. 😀
With that out of the way, here’s what I started with. First I created a QUnit and Scripts Directory. In QUnit I placed the qunit.css and qunit.js files and in the Scripts Directory I added the jquery-1.5.1.min.js file. The later file isn’t that important at this point, but I’ve added it since I intend to use it at some point later on.
There are a few main ideas behind doing a Code Kata:
Keep the implementation code to the absolute minimum needed to pass the test.
Use a steady TDD/BDD Style testing first approach to think through each step.
[sourcecode language=”html”]
<!DOCTYPE HTML>
<html>
<head>
<title>TimePiece Object Unit Tests</title>
<link rel="stylesheet"
href="../QUnit/qunit.css"
type="text/css"
media="screen"/>
<script type="text/javascript"
src="../Scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript"
src="../QUnit/qunit.js"></script>
<script type="text/javascript">
// All the code bits go here!
</script>
<body>
<p>Roman to Arabic, Arabic to Roman…</p>
<span>QUnit Test Results…</span>
Which gets me to the point that I have a rendering of an empty test results page, as shown below.
QUnit Test Results Page
The next step was to get started. So jumping right in I got some code put in place for a failing test.
[sourcecode language=”JavaScript”]
module("When converting an integer into a roman numeral");
test("should receive I when passing a 1", function() {
equal(NumeralConverter.get_arabic_numeral("I"), 1, "I was returned when 1 was passed as a parameter.");
});
[/sourcecode]
Red light received, code committed, implementing for green.
[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
return 1;
}
}
[/sourcecode]
Code committed. Sticking with the idea to implement the bare minimum needed, one can see pretty obviously that this isn’t much of a converter. So going forward I added the next test, for our second numeral.
[sourcecode language=”JavaScript”]
test("should receive 2 when passing a ‘II’", function() {
equal(NumeralConverter.get_arabic_numeral("II"), 2, "2 was returned when ‘II’ was passed as a parameter.");
});
[/sourcecode]
Again, nothing really specific here, nor is any defined logic really visible in what the method is needing to do. So after the commit I implemented the logic to pass this and committed this also.
[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
var result = romanNumeral == "I" ? 1 : 2;
return result;
}
}
[/sourcecode]
That gets those bits passing. With a nice little JavaScript Ternary Operator. Still not hitting on the big picture of converting between the roman to arabic numerals yet, but we’re getting a little closer. Stepping up to the next test, pretty much more of the same.
[sourcecode language=”JavaScript”]
test("should receive 3 when passing a ‘III’", function() {
equal(NumeralConverter.get_arabic_numeral("III"), 3, "3 was returned when ‘III’ was passed as a parameter.");
});
[/sourcecode]
With the failing test committed, I did what seems like the easiest solution, yet so much like it is cheating. But hey! It works! That’s what is is about and one ever knows what kind of alternate solutions will crop up! Think small steps and things will lay out for you in interesting ways. Discipline!
[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
return romanNumeral.length;
}
}
[/sourcecode]
So now the first tricky one comes up, the IV. The test continues to repeat. I pondered a rowset style test, but wasn’t really happy with any of the prospective solutions I saw with a quick search on the net for qunit. So on with tests as I’ve been going.
[sourcecode language=”JavaScript”]
test("should receive 4 when passing a ‘IV’", function() {
equal(NumeralConverter.get_arabic_numeral("IV"), 4, "4 was returned when ‘IV’ was passed as a parameter.");
});
[/sourcecode]
Red light received, code committed. The implementation for this, still feels like cheating. Simplest code to get the test passing possible.
Green light, code committed. Again, straight into a test.
[sourcecode language=”JavaScript”]
test("should receive 5 when passing a ‘V’", function() {
equal(NumeralConverter.get_arabic_numeral("V"), 5, "5 was returned when ‘V’ was passed as a parameter.");
});
[/sourcecode]
Green light. Code committed. It seems like something is starting to brew up out of the method.
[sourcecode language=”JavaScript”]
test("should receive 6 when passing a ‘VI’", function() {
equal(NumeralConverter.get_arabic_numeral("VI"), 6, "6 was returned when ‘VI’ was passed as a parameter.");
});
[/sourcecode]
Green light, code committed. I implemented the next bits, but at testing that VIII returns 8 I began a refactoring. If I were to split the one Roman Numerals ‘I’ off I could then just count their length and add them to the five Roman Numeral V. I didn’t really think about how that would work past 8, but it seemed like a valid refactoring. After that, these two additional tests were completed and passing.
[sourcecode language=”JavaScript”]
test("should receive 7 when passing a ‘VII’", function() {
equal(NumeralConverter.get_arabic_numeral("VII"), 7, "7 was returned when ‘VII’ was passed as a parameter.");
});
test("should receive 8 when passing a ‘VIII’", function() {
equal(NumeralConverter.get_arabic_numeral("VIII"), 8, "8 was returned when ‘VIII’ was passed as a parameter.");
});
[/sourcecode]
The actual method implementation looked like this now.
[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
var ones = 0;
var five = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length -1;
var iCount = romanNumeral.split(/I/g).length – 1;
Now we’re actually getting some logic in there. If one breaks the rules, there is even a bit of foreshadowing to where the logic and looping will eventually end up. But I’m going to keep going with the KISS idea and doing a minimal implement for each failing test! Moving right along…
[sourcecode language=”JavaScript”]
test("should receive 9 when passing a ‘IX’", function() {
equal(NumeralConverter.get_arabic_numeral("IX"), 9, "9 was returned when ‘IX’ was passed as a parameter.");
});
[/sourcecode]
Ok, ok, now at this point I’m thinking, “oh jeez, this list of tests looks like a mess. These need refactored now.” I did look for a rowtest earlier, and that didn’t exist really. So something else ought to work though, but the question is what? So I looked around and just took a few minutes to think. Take a look at the tests at this point all listed together.
[sourcecode language=”JavaScript”]
module("When converting a roman numeral into an arabic numeral");
test("should receive 1 when passing a ‘I’", function() {
equal(NumeralConverter.get_arabic_numeral("I"), 1, "1 was returned when ‘I’ was passed as a parameter.");
});
test("should receive 2 when passing a ‘II’", function() {
equal(NumeralConverter.get_arabic_numeral("II"), 2, "2 was returned when ‘II’ was passed as a parameter.");
});
test("should receive 3 when passing a ‘III’", function() {
equal(NumeralConverter.get_arabic_numeral("III"), 3, "3 was returned when ‘III’ was passed as a parameter.");
});
test("should receive 4 when passing a ‘IV’", function() {
equal(NumeralConverter.get_arabic_numeral("IV"), 4, "4 was returned when ‘IV’ was passed as a parameter.");
});
test("should receive 5 when passing a ‘V’", function() {
equal(NumeralConverter.get_arabic_numeral("V"), 5, "5 was returned when ‘V’ was passed as a parameter.");
});
test("should receive 6 when passing a ‘VI’", function() {
equal(NumeralConverter.get_arabic_numeral("VI"), 6, "6 was returned when ‘VI’ was passed as a parameter.");
});
test("should receive 7 when passing a ‘VII’", function() {
equal(NumeralConverter.get_arabic_numeral("VII"), 7, "7 was returned when ‘VII’ was passed as a parameter.");
});
test("should receive 8 when passing a ‘VIII’", function() {
equal(NumeralConverter.get_arabic_numeral("VIII"), 8, "8 was returned when ‘VIII’ was passed as a parameter.");
});
test("should receive 9 when passing a ‘IX’", function() {
equal(NumeralConverter.get_arabic_numeral("IX"), 9, "9 was returned when ‘IX’ was passed as a parameter.");
});
[/sourcecode]
That’s a lot of tests. Well, I looked through the documentation a little bit, and realized that I could just do this. Is it more readable? It almost comes off as rowset tests in junit/nunit.
[sourcecode language=”JavaScript”]
module("When converting a roman numeral into an arabic numeral");
test("should receive arabic numeral", function() {
equal(NumeralConverter.get_arabic_numeral("I"), 1, "1 when ‘I’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("II"), 2, "2 when ‘II’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("III"), 3, "3 when ‘III’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("IV"), 4, "4 when ‘IV’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("V"), 5, "5 when ‘V’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("VI"), 6, "6 when ‘VI’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("VII"), 7, "7 when ‘VII’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("VIII"), 8, "8 when ‘VIII’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("IX"), 9, "9 when ‘IX’ was passed as a parameter.");
});
[/sourcecode]
Either way, I’m sticking to it for now. I added the test for X.
[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("X"), 10, "10 when ‘X’ is passed in.");
[/sourcecode]
Then implemented it following a similar pattern that I had already started.
[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;
That was easy enough. Also note, when the pattern that is now evident among the logic, the next two tests automatically pass. Now some real progress has been made.
[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("XI"), 11, "11 when ‘XI’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XII"), 12, "12 when ‘XII’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XIII"), 13, "13 when ‘XIII’ is passed in.");
[/sourcecode]
Now however, things get a bit tricky. Add a test for ‘VX’.
[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("VX"), 14, "14 when ‘VX’ is passed in.");
[/sourcecode]
So adding another simple exception, pretty much takes care of that.
[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;
Green light. Code Commit. Now for the next three tests, they’ll all pass. The next test that we run into that gives us a failing test is for 19, or ‘XIX’. For the tests below I went ahead and added XVI, XVII, and XVIII.
[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("XVI"), 16, "16 when ‘XVI’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XVII"), 17, "17 when ‘XVII’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XVIII"), 18, "18 when ‘XVIII’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XVIII"), 19, "19 when ‘XIX’ is passed in.");
[/sourcecode]
Red light, code commit.
[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;
Green light, code commit. Add the test for ‘XX’ and you’ll find that this test automatically passes also. There’s still soemthing to be done about the odd else if assigned values above! But onward. After the test for ‘XX’, I’ll jump right in and see how far I can get. Not until 24 do I run into an issue.
[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("XXI"), 21, "21 when ‘XXI’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XXII"), 22, "22 when ‘XXII’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XXIII"), 23, "23 when ‘XXIII’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XXIV"), 24, "24 when ‘XXIV’ is passed in.");
[/sourcecode]
It seems like there is some type of logic happening, some repeatable logic. So I started giving it a good look over. I will admit, I went ahead and worked through several more of the tests and implementation details just to force more of the if else statements to be apparent. I added tests for 25-30 and implemented passing tests with the following code.
[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;
I started to stop and do research, look up some other functions that already do this. I wanted to bad, but I stuck with the original idea behind the Kata. Just implement the bare minimum code and go through the red, green, refactor approach. In the end I stuck with that approach and came up with this mess.
[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;
if (romanNumeral.length > 1) {
if (romanNumeral == "IV" || romanNumeral == "IX") {
var workingNumber = fives + tens – iCount;
return workingNumber;
}
else if (romanNumeral == "XIV") {
return 14;
}
else if (romanNumeral == "XIX") {
return 19;
}
else if (romanNumeral == "XXIV") {
return 24;
}
else if (romanNumeral == "XXIX") {
return 29;
}
}
ones = iCount;
result = fives + ones + tens;
return result;
}
[/sourcecode]
From here, I had to get the IV or IX off of the larger roman numerals. I needed some string capabilties, so I pulled in some libraries for string manipulation, namely the Underscore.js + Underscore.string libraries. After that refactor, I knocked out all the code (yup, deleting code!) around the extra else if statements.
[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;
if (romanNumeral.length > 1) {
if (_(romanNumeral).endsWith("IV") || _(romanNumeral).endsWith("IX")) {
var workingNumber = fives + tens – iCount;
return workingNumber;
}
}
ones = iCount;
result = fives + ones + tens;
return result;
}
[/sourcecode]
At this point I was fairly confident that I had a huge number of effective conversions. So I decided to skip a few tests and head into the other numbers and other exception criteria. I did a commit for the refactor that I just finished and then jumped into a test for L, the Roman Numeral which represents 50, and the other numbers M, D, and C. I did write these individually, and then added the code, but I’ve added them altogether here to conserve space in this already long blog entry. 😉
[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("L"), 50, "50 when ‘L’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("M"), 1000, "1000 when ‘M’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("D"), 500, "500 when ‘D’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("C"), 100, "100 when ‘C’ is passed in.");
[/sourcecode]
Red light, committed code. Implement.
[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0, fifties = 0;
var hundreds = 0, fiveHundreds = 0, thousands = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;
var lCount = romanNumeral.split(/L/g).length – 1;
var cCount = romanNumeral.split(/C/g).length – 1;
var dCount = romanNumeral.split(/D/g).length – 1;
var mCount = romanNumeral.split(/M/g).length – 1;
At this point, one can see some of the changes from refactoring, and the practice of TDD for this specific kata. It is a great way to become more efficient at thinking in a TDD way, or a touch of how one might do BDD. I hope to have more blog entries about BDD vs. TDD, how to do this, and how to get better at it. Of course, I can only write about what I know or am learning myself, and with this particular occupation I’m always learning. 😉
Hopefully this was useful, as material and as an idea. I’m not 100% finished with this kata, and I will post the code in its completed form once I’m done. For now, enjoy, and practice that TDD/BDD awesomeness!
You must be logged in to post a comment.