Your Ad Here

Monday, February 18, 2008

Decimal Value to Roman Numeral - Algorithm 2

If you haven't seen the earlier algorithm to change Decimal Values to Roman Numerals you can read that blog here: Decimal Values to Roman Numeral Algorithm 1.

The following code represents a shorter algorithm that should be easy enough to understand. Algorithm 2 does away with the cumbersome IF statements from the previous algorithm and wraps up all the conversions in one WHILE loop. This function the same principle as that used in the previous algorithm, but instead of hard coding all the values of the Roman Numeral characters and pairs into separate IF and WHILE clauses, the values and characters are stored in a couple of arrays and referenced in a single WHILE loop. I have not compared the speeds of the two algorithms demonstrated here and in Decimal Values to Roman Numeral Algorithm 1. The speed tests will be covered in a later blog, but for now, here's the code written in VB .NET:

DECIMAL to ROMAN Algorithm 2

Private Sub cmdConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdConvert.Click

' Declare and initialize all variables. Roman Numerals and their standard combinations
' are stored in strRoman. The corresponding values are stored in intDecimal.

Dim strRoman() As String = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
Dim intDecimal() As Integer = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
Dim intInput As Integer = Nothing ' Numeric representation of the input field.
Dim intTemp As Integer = Nothing ' Used to store the magnitude of each decimal digit.
Dim intPointer As Short = 0 ' Pointer to the Roman and Decimal arrays, starts at the first cell.
Dim intCountI As Short = Nothing ' Temporary variable used for loops.

intInput = CInt(txtInput.Text) ' Convert the string in the input field to an integer.
txtOutput.Clear() ' Clear the contents of the output field.

While intInput > 0 ' Check to see if intInput still has any value left in it.
intTemp = intInput \ intDecimal(intPointer) ' See how many of the currently selected value can fit in the remaining input.

For intCountI = 1 To intTemp
txtOutput.Text += strRoman(intPointer) ' Append a number of Roman Characters depending on the value of intTemp.

intInput -= intTemp * intDecimal(intPointer) ' Subtract the value of the characters that were appended to output from the input.
intPointer += 1 ' Move the pointer to the next cell of the arrays.
End While

End Sub

You can download a ZIP file with all the VB .NET project files and an executable using this algorithm here. You can also see several other algorithm implementations at the Computer Science 101 website.

1 comment:

Anonymous said...


This forum rocks. Nice to be here.

So long