The Obvious Pattern
Here's the code. Can you see a pattern? It kinda jumps out now right?
Public Function i2r(i As Integer) As String
Application.Volatile
i2r = ""
If i >= 10 Then
i2r = i2r + "X"
i = i - 10
End If
If i = 9 Then
i2r = i2r + "IX"
i = i - 9
End If
If i >= 5 Then
i2r = i2r + "V"
i = i - 5
End If
If i = 4 Then
i2r = i2r + "IV"
i = i - 4
End If
While i >= 1
i2r = i2r + "I"
i = i - 1
Wend
End Function
I try, but fail, to add a function which I can use to move all that repeating code ... but I've not coded for a long time and I fail. Out of laziness and lack of imagination I give up and decide to add more test cases first.
I add a test case for 16 =XVI and then I get enthusiastic and add the tests into the spreadsheets for 17 through to 19. I think they should work straight away and they do.
I add 20 = XX and it doesn’t work immediately.
I look at the code and quickly change the IF i >= 10 to a while loop.
Hmmmm, I think. I reckon that these tests should now work all the way to 50.
So I add in the integer values from 21 – 30 and instead of filling in the roman numerals, I cheat a little and copy down the i2r() function and eyeball them to check that they’re right. They all are so I copy the values from my function into the test data.
Then I chose a few other numbers up to 50, which I figure will fail with the current code. But, when I type in 46 I realise that the 40’s are a special case like 4 and 9, and later on 90, 400 and 900. So I check google to find out what the symbol for 40 is … it’s XL. I add in the test case for 40 and make it work.
I add in a test case for 49 and it works. I’m confident that the rest of the 40’s will work too.
I add in a test case for 50 = l and as expected it doesn’t work. By now, the code is trivial so I make it work.
Then I think about doing some more Refactoring.