Tag Archives: kata

______11 |> F# – Some Hackery – A String Calculator Kata

Now for some F# hacking. The first thing I did was actually go through a Code Kata, which I’ll present here.

The first step I took was to get a project started. For that I used the ProjectScaffold to build a clean project via bash.

First cloned…

git clone git@github.com:fsprojects/ProjectScaffold.git sharpKataStringCalc

…then I navigated into the directory and executed the build.sh script…

cd sharpKataStringCalc/
./build.sh

…then I got prompted for some input.

  #####################################################

# 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):

Once I hit enter after entering the information I’ve gotten more than a few of these broken builds.

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
---------------------------------------------------------------------

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.

Finished Target: GenerateReferenceDocs
Starting Target: GenerateDocs (==> GenerateReferenceDocs, GenerateReferenceDocs)
Finished Target: GenerateDocs
Starting Target: All (==> GenerateDocs)
Finished Target: All

---------------------------------------------------------------------
Build Time Report
---------------------------------------------------------------------
Target                  Duration
------                  --------
Clean                   00:00:00.0035253
AssemblyInfo            00:00:00.0103142
Build                   00:00:04.9369669
CopyBinaries            00:00:00.0052210
RunTests                00:00:00.6568475
CleanDocs               00:00:00.0025772
GenerateHelp            00:00:08.6989318
GenerateReferenceDocs   00:00:11.7627584
GenerateDocs            00:00:00.0003409
All                     00:00:00.0000324
Total:                  00:00:26.1162623
Status:                 Ok
---------------------------------------------------------------------

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.

./build.sh RunTests

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

  1. Create a simple String calculator with a method int Add(string numbers)
    1. 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”
    2. Start with the simplest test case of an empty string and move to 1 and two numbers
    3. Remember to solve things as simply as possible so that you force yourself to write tests you did not think about
    4. Remember to refactor after each passing test
  2. Allow the Add method to handle an unknown amount of numbers.
  3. Allow the Add method to handle new lines between numbers (instead of an empty space).
    1. the following input is ok: “1\n2 3” (will equal 6)
    2. the following input is NOT ok: “1 \n” (not need to prove it – just clarifying)
  4. Support different delimiters
    1. 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 ‘;’ .
    2. the first line is optional. all existing scenarios should still be supported
  5. 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
  6. Numbers bigger than 1000 should be ignored, so adding 2 + 1001 = 2
  7. Delimiters can be of any length with the following format: “//[delimiter]\n” for example: “//[***]\n1***2***3” should return 6
  8. Allow multiple delimiters like this: “//[delim1][delim2]\n” for example “//[*][%]\n1*2%3” should return 6.
  9. 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.

module sharpKataStringCalc.Tests

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)

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.

namespace sharpKataStringCalc

open System

type Calculator() = 
  member x.Add express = 
    0

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.

  [<TestCase("1", Result = 1)>]
  member x.Add_single_number_returns_that_number expression =
    let calculator = Calculator()
    calculator.Add expression

I ended up with something like this then.

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

After adding that code with that little refactor I ran it, red light fail, so I then moved on to implementation for this test.

type Calculator() = 
  member x.Add expression = 
    match expression with
    | "" -> 0
    | _ -> 1

Everything passed. So now on to the next scenario other subsequent number strings. I add another test and result condition.

  [<TestCase("1", Result = 1)>]
  [<TestCase("2", Result = 2)>]
  member x.Add_single_number_returns_that_number expression =
    calculator.Add expression

It runs, gets a red light fail, I then implement with this minor addition.

type Calculator() = 
  member x.Add expression = 
    match expression with
    | "" -> 0
    | _ -> Int32.Parse expression

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.

  [<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

Fails, so on to implementation. I’m just going to do this the cheap “it works” way and do something dumb.

type Calculator() = 
  member x.Add expression = 
    match expression with
    | "" -> 0
    | _ when expression.Contains " " -> 3
    | _ -> Int32.Parse expression

That’ll give me a passing green light, but I’ll add another bit of attribute to the test and get another failing test.

  [<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

I’ll add the following code to implement and get a passing test.

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

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.

[<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

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.

Reference:

Code Katas: Kicking off With a Little JavaScript

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.
<!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>

    <h1 id="qunit-header">Numeral Conversions</h1>

    <h2 id="qunit-banner"></h2>

    <div id="qunit-testrunner-toolbar"></div>
    <h2 id="qunit-userAgent"></h2>
    <ol id="qunit-tests"></ol>
    <div id="qunit-fixture">hidden text</div>
</body>
</html>

Which gets me to the point that I have a rendering of an empty test results page, as shown below.

QUnit Test Results Page

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.

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.");
});

Red light received, code committed, implementing for green.

var NumeralConverter = {
    get_arabic_numeral : function ( romanNumeral ){
        return 1;
    }
}

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.

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.");
});

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.

var NumeralConverter = {
    get_arabic_numeral : function ( romanNumeral ){
        var result = romanNumeral == "I" ? 1 : 2;
        return result;
    }
}

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.

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.");
});

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!

var NumeralConverter = {
    get_arabic_numeral : function ( romanNumeral ){
        return romanNumeral.length;
    }
}

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.

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.");
});

Red light received, code committed. The implementation for this, still feels like cheating. Simplest code to get the test passing possible.

var NumeralConverter = {
    get_arabic_numeral : function ( romanNumeral ){
        if(romanNumeral == "IV"){
            return 4;
        }
        return romanNumeral.length;
    }
}

Green light, code committed. Again, straight into a test.

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.");
});

Red light, code committed.

var NumeralConverter = {
    get_arabic_numeral : function ( romanNumeral ){
        if(romanNumeral == "IV"){
            return 4;
        }
        else if(romanNumeral == "V"){
            return 5;
        }
        return romanNumeral.length;
    }
}

Green light. Code committed. It seems like something is starting to brew up out of the method.

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.");
});

Red light. Code committed.

var NumeralConverter = {
    get_arabic_numeral : function ( romanNumeral ){
        if(romanNumeral == "IV"){
            return 4;
        }
        else if(romanNumeral == "V"){
            return 5;
        }
        else if(romanNumeral == "VI"){
            return 6;
        }
        return romanNumeral.length;
    }
}

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.

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.");
});

The actual method implementation looked like this now.

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;

        if(romanNumeral == "IV"){
            return 4;
        }
        else if(vCount > 0){
            five = vCount * 5;
        }

        ones = iCount;
        result = five + ones;

        return result;
    }
}

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…

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.");
});

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.

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.");
});

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.

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.");
});

Either way, I’m sticking to it for now. I added the test for X.

equal(NumeralConverter.get_arabic_numeral("X"), 10, "10 when 'X' is passed in.");

Then implemented it following a similar pattern that I had already started.

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 == "IV") {
        return 4;
    }
    else if (romanNumeral == "IX") {
        return 9;
    }
    else if (vCount > 0) {
        fives = vCount * 5;
    }
    else if (xCount > 0) {
        tens = xCount * 10;
    }

    ones = iCount;
    result = fives + ones + tens;

    return result;
}

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.

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.");

Now however, things get a bit tricky. Add a test for ‘VX’.

equal(NumeralConverter.get_arabic_numeral("VX"), 14, "14 when 'VX' is passed in.");

So adding another simple exception, pretty much takes care of that.

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 == "IV") {
        return 4;
    }
    else if (romanNumeral == "IX") {
        return 9;
    }
    else if(romanNumeral == "VX") {
        return 14;
    }
    else if (vCount > 0) {
        fives = vCount * 5;
    }
    else if (xCount > 0) {
        tens = xCount * 10;
    }

    ones = iCount;
    result = fives + ones + tens;

    return result;
}

Now that trickiness comes up when adding the test for ‘XV’.

equal(NumeralConverter.get_arabic_numeral("XV"), 15, "15 when 'XV' is passed in.");

Red light, code commit. Now to implement. An actual reduction of code gets us back in action here.

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 == "IV") {
        return 4;
    }
    else if (romanNumeral == "IX") {
        return 9;
    }
    else if (romanNumeral == "VX") {
        return 14;
    }
    else if (vCount > 0 || xCount > 0) {
        fives = vCount * 5;
        tens = xCount * 10;
    }

    ones = iCount;
    result = fives + ones + tens;

    return result;
}

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.

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.");

Red light, code commit.

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 == "IV") {
        return 4;
    }
    else if (romanNumeral == "IX") {
        return 9;
    }
    else if (romanNumeral == "VX") {
        return 14;
    }
    else if (romanNumeral == "XIX") {
        return 19;
    }
    else if (vCount > 0 || xCount > 0) {
        fives = vCount * 5;
        tens = xCount * 10;
    }

    ones = iCount;
    result = fives + ones + tens;

    return result;
}

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.

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.");

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.

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 == "IV") {
        return 4;
    }
    else if (romanNumeral == "IX") {
        return 9;
    }
    else if (romanNumeral == "XIV") {
        return 14;
    }
    else if (romanNumeral == "XIX") {
        return 19;
    }
    else if (romanNumeral == "XXIV") {
        return 24;
    }
    else if (romanNumeral == "XXIX") {
        return 29;
    }
    else if (vCount > 0 || xCount > 0) {
        fives = vCount * 5;
        tens = xCount * 10;
    }

    ones = iCount;
    result = fives + ones + tens;

    return result;
}

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.

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 (vCount > 0 || xCount > 0) {                        
        fives = vCount * 5;                                
        tens = xCount * 10;                                
    }                                                      
                                                           
    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;                                         
}                                                          

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.

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 (vCount > 0 || xCount > 0) {
        fives = vCount * 5;
        tens = xCount * 10;
    }

    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;
}

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. 😉

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.");

Red light, committed code. Implement.

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;

    if (vCount > 0 || xCount > 0 || lCount > 0 || cCount > 0 || dCount > 0 || mCount > 0) {
        fives = vCount * 5;
        tens = xCount * 10;
        fifties = lCount * 50;
        hundreds = cCount * 100;
        fiveHundreds = dCount * 500;
        thousands = mCount * 1000;
    }

    if (romanNumeral.length > 1) {
        if (_(romanNumeral).endsWith("IV") || _(romanNumeral).endsWith("IX")) {
            var workingNumber = fives + tens - iCount;
            return workingNumber;
        }
    }

    ones = iCount;
    result = ones + fives + tens + fifties + hundreds + fiveHundreds + thousands;

    return result;
}

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!

Kōans of Code

I’ve continued the Kōans, but there is one thing that won’t be noticeable from this blog entry. I however wanted to mention it. The first blog entry was worked through on an OS-X Apple Machine, the second on an Ubunta Linux Machine, and now I’m heading for this blog entry to be completed with  Windows 7. It is of course completely irrelevant, but at the same time very relevant.  🙂 But enough about operating system awesomeness. Let’s take a look at the new gazillion Kōans that caught my note taking.

class AboutArrays < EdgeCase::Koan
  def test_creating_arrays
    empty_array = Array.new
    assert_equal Array, empty_array.class
    assert_equal 0, empty_array.size
  end

Easy peasy. Array.new creates a new empty array. Got it. An Array is the class type retrieved when calling empty_array.class. Got it. The empty array has a size of zero, Got it.

  
  def test_array_literals
    array = Array.new
    assert_equal [], array
  
    array[0] = 1
    assert_equal [1], array
  
    array[1] = 2
    assert_equal [1, 2], array
  
    array << 333
    assert_equal [1, 2, 333], array
  end

Ok, this one has some interesting bits in it. Having array[0] and array[1] assigned to a value of 1 and 2 seems standard operating practice for a language. This dual chevrons pointing into the array thing is a little more unique. This operator appears to take the value on the right, and put it onto the array’s stack. Simply, the double kick operator (or whatever it is called) puts the value on the next available array index position. Ok, cool. Got it.

    
  def test_accessing_array_elements
    array = [:peanut, :butter, :and, :jelly]
  
    assert_equal :peanut, array[0]
    assert_equal :peanut, array.first
    assert_equal :jelly, array[3]
    assert_equal :jelly, array.last
    assert_equal :jelly, array[-1]
    assert_equal :butter, array[-3]
  end

Alright, got an array with 4 elements in it. First assert confirms that :peanut is the returned value from the first element in the array. The array.first call functionally does the same thing. The third assert gets the 3rd value in the array, keeping in mind a zero based index for the array, that gives us the 4th actual item in the list of items stored within the array. I love it, standard programmer weirdness. Why do programmers start with zero when nobody on earth starts a “list” of items with a zero. Blagh, whatever, that’s the reality of it. (That was, in a sense, somewhat rhetorical, I get the underlying reasons but that doesn’t help explain a zero based index to initial non-programmers.)

  
  def test_slicing_arrays
    array = [:peanut, :butter, :and, :jelly]
  
    assert_equal [:peanut], array[0,1]
    assert_equal [:peanut, :butter], array[0,2]
    assert_equal [:and, :jelly], array[2,2]
    assert_equal [:and, :jelly], array[2,20]
    assert_equal [], array[4,0]
    assert_equal [], array[4,100]
    assert_equal nil, array[5,0]
  end

Slicing arrays again with the PB & J. With two values, the first thing I notice is that this is no multidimensional array. Two values within the square brackets means that you have a starting position and then a value of how many to retrieve. If there is a value like the fourth asset, starting at the 2nd position (3rd actual value) and taking the next 20 elements, basically retrieves whatever values are available, which in this case gets us 2 elements.

Now, I’m a slight bit perplexed though as to why nil is returned for something request nothing from the 5th starting point of the array versus the same being requested from the 4th starting point in the array. I’ll have to read up on that…

    
  def test_arrays_and_ranges
    assert_equal Range, (1..5).class
    assert_not_equal [1,2,3,4,5], (1..5)
    assert_equal [1,2,3,4,5], (1..5).to_a
    assert_equal [1,2,3,4], (1...5).to_a
  end

Again, identifying the class object type is easy, a range of numbers is a Range Object. Check. A range stating 1..5 does not provide the numbers one through five. Calling to_a on a range however does provide you those numbers. Doing the same thing to an array specified with three periods instead of two with the to_a provides numbers one through four. That seems odd, but I got it.

  
  def test_slicing_with_ranges
    array = [:peanut, :butter, :and, :jelly]

    assert_equal [:peanut, :butter, :and], array[0..2]
    assert_equal [:peanut, :butter], array[0...2]
    assert_equal [:and, :jelly], array[2..-1]
    assert_equal [:peanut, :butter, :and], array[0..-2]
  end

Slicing an array of four values, stating the starting and ending point with the syntax of a range, provides the elements based on the values associated with that range. I actually added an assert to this test to determine what exactly the negative values do. It appears that the array starts at the point of the first number, then follows a range from that until the negative number from the end of the array. So with 10 items, starting at point 2 and ending -2 from the end will retrieve the middle 6 elements. Strange, but I can see how this would be very useful.

    
  def test_pushing_and_popping_arrays
    array = [1,2]
    array.push(:last)
  
    assert_equal [1,2,:last], array
  
    popped_value = array.pop
    assert_equal :last, popped_value
    assert_equal [1, 2], array
  end

Pop. Easy, get that last value. But wait a second, the array itself doesn’t have :last in it? Aha! Popping it not only gets that last value, but literally takes the value out of the array.

  
  def test_shifting_arrays
    array = [1,2]
    array.unshift(:first)
  
    assert_equal [:first, 1, 2], array
  
    shifted_value = array.shift
    assert_equal :first, shifted_value
    assert_equal [1,2], array
  end
  
end

Ah, kind of like a popped value but shifted out of the array? Weird, this is a little confusing at first. I see what it is appearing to do, but figured a good read of the documentation would be good. I did a search on Google and the first hit is someone asking this question.

What does Ruby’s Array Shift Do?

From that quick read it appears that shift and unshift are used similar to pop and push in a stack (ala git, etc).

That answers that question. With that, I’m off to other realms.

Kata Kickin’ Some Prime Numbers

Lately I have been interviewing people for prospective positions in the company I work for.  In the various questions that I and others pose during these interviews one popped up as a prospective Kata.  The challenge is really quit simple, “Write a method that would take a int and check if it is a prime number.”  The following snippet is what I came up with.

protected bool IsPrime(int theNumber) 
{ 
    bool isPrime = true;

    int theHalf = theNumber / 2;

    for (int i = 2; i < theHalf; i++) 
    { 
        var remainder = theNumber % i; 
        if (remainder == 0) 
        { 
            isPrime = false; 
            break; 
        } 
    }

    return isPrime; 
}

The next idea that popped up was to find X prime number in order.  As the answer a question like, “What is the 6th prime number?”  I came up with the following method for that.

protected int GetPrimeByPosition(int position) 
{ 
    int counter = 1; 
    int thePosition = 0; 
    while (true) 
    { 
        if(IsPrime(counter)) 
        { 
            if(thePosition == position) 
                return counter; 
            thePosition++; 
        }

        counter++; 
    } 
}

In the end the Kata is a simple 2 step problem.

  1. Write a method that determines if an int is a prime number.  i.e. “Is 5 a prime number?”
  2. Write a method that determines the prime number based on X order.  i.e. “What is the 3rd prime number?”

So based on these two steps, what would be some other steps to add to this Kata?  What are some other good interview questions that are short and simple for prospective employees to code through?

More Cloud News

Recently Amazon jumped into the relational database cloud competition with Microsoft.  Up until the 6th of this month, Microsoft had the only cloud with a real dedicated relational database offering in SQL Azure.  Now Amazon has their Relational Database Service heating up the competition.

In other news, Google finally joined the storage party with their recent launch announcement at the I/O Conference.  So now we have Amazon, Microsoft, and Google as the big companies on the block throwing down on the storage offerings.  Stay tuned for more!

In other news I have been working through the katas setup for TDD practice.  They’re actually a lot of fun and would suggest anyone out there interested in TDD or just unit testing to just go out and give one a test drive.  : )

Currently I am working on a code kata putting together ideas from Roy Osherove‘s The Art of Unit Testing and what one needs to know for testing in enterprise environments, abstracting the appropriate code to take into account web services, files, I/O, architectural issues, and other elements of coding.