Mountain Gold
Mountain Gold

Reputation: 131

Avoidable if-else

Here is a finished Roman to Decimal numeral convertor.

Dictionary<char,int> nTrans = new Dictionary<char,int>();
            nTrans.Add('I',1);
            nTrans.Add('V', 5);
            nTrans.Add('X', 10);
            nTrans.Add('L', 50);
            nTrans.Add('C', 100);
            nTrans.Add('D', 500);
            nTrans.Add('M', 1000);

            string rNum = "XV";
            int dNum = 0;

            for (int i = 0; i < rNum.Length; i++)
            {
                if (i < rNum.Length-1)
                {
                    if (nTrans[rNum[i]] < nTrans[rNum[i + 1]])
                    {
                        dNum -= nTrans[rNum[i]];
                    }
                    else
                    {
                        dNum += nTrans[rNum[i]];
                    }
                }
                else
                {
                    dNum += nTrans[rNum[i]];
                }
            }

But I can't figure out how to escape from using this if-else statement:

if (i < rNum.Length-1)
{
//Code
}
else
{
dNum += nTrans[rNum[i]];
}

Any suggestions how I can avoid using it? The question is only for optimizing and improving my coding skills!

Upvotes: 0

Views: 108

Answers (2)

NimChimpsky
NimChimpsky

Reputation: 47280

Case statements can improve readability, or also a command map/dictionary, where each calculation is stored in dictionary/map and looked up directly.

Upvotes: -2

Anna
Anna

Reputation: 135

Can you process everything between 0 and rNum.Length - 1 in the loop, and then process the last one outside of it?

Something like:

for (int i = 0; i < rNum.Length - 1; i++)
{
// do regular stuff
}

if (rNum.Length != 0)
    dNum += nTrans[rNum[rNum.Length - 1]];

If this is in a function, you can move the rNum.Length == 0 check to the top and just return 0 as dNum if it is true. That way you skip all the extra processing.

Upvotes: 3

Related Questions