Click here to Skip to main content
15,892,927 members
Articles / Programming Languages / C#

Coding Challenge Lesson Learnt

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
21 Feb 2017CPOL4 min read 4.8K   1  
Coding challenge lesson learnt

Table of Contents

Introduction

Last month, I joined a coding challenge fun at codeproject.com. The theme for the challenge was "convert integer to a sentence". For example: 12345 or 12,345 would result in Twelve thousand, three hundred and forty-five. Of course, I didn’t win, there were way too many smart contestants out there. Anyway, looking back, I think there are several points I can share from the code that I wrote. Here is the link to the code: http://rextester.com/FTS88296.

NumberStyles

The code was structured to accept both numeric string with and without number styles. At one point, I was getting the error "Message: "Input string was not in a correct format."" when parsing the input with comma and negative sign into integers. Then I realized that I need to include NumberStyles in the integer parse method, basically the integer parser need to know the numeric string can contains certain symbol. To be honest, I forgot the syntax!!! Luckily, I found what I’m looking for on the MSDN site to help refresh my memory. Here is the link to NumberStyles Enumeration. The resource lists all the NumberStyles members and provides example on how to include multiple NumberStyles into the int.parse method. I figure if I write this down, it will come in handy once in a while by searching my blog.
Listing 1 shows how to parse a numeric string into 64-bit signed and unassigned integers respectively.

Listing 1

C#
 if (Int64.TryParse(input, NumberStyles.AllowThousands | 
                    NumberStyles.AllowLeadingSign, provider, out userInput))
 {
      Console.WriteLine(IntegerToSentence(userInput));
 }
 else if (UInt64.TryParse(input, NumberStyles.AllowThousands, provider, out userInputUnsigned))
 {
      Console.WriteLine(IntegerToSentence(userInputUnsigned));
}

Tuple

I also use 2-tuple or pair in the code. Here is the link to learn more about Tuple Class. Listing 2 shows how to declare a method with return 2-tuple type and how to create 2-tuple object. In this example, the first object holds a Boolean value indicating if the integers are positive or negative. The second object holds a list of integer converted to string.

Listing 2

C#
public static Tuple<bool, IList<string>> 
GroupInteger<T>(this T input, int groupLength = 3)
{
 …
Tuple<bool, IList<string>> listNumbers = new Tuple<bool, 
IList<string>>(isNegative, groupNumbers);
…
}

Listing 3 shows how to access the 2-tuple elements.

Listing 3

C#
//minus sign
if (listInteger.Item1)
{
output += "Minus ";
}
//number of group
j = listInteger.Item2.Count - 1;

In my opinion, the nice feature about tuple class is that it acts like a container, it can hold any object. And every time I think of or come across 6-tuple, it makes me chuckle a little bit. I always think why can't we call it sixtuple or hextuple instead of sextuple.

Generic Extension Method

The code also utilized a generic extension method that will take 64-bit signed and unassigned integers as a parameter.

Listing 4 shows how to create a generic extension method with multiple parameters. The first parameter with "this" keyword is a required parameter for extension method. I added the second parameter and set it as optional.

Listing 4

C#
public static class Utility
{
	public static Tuple<bool, IList<string>> 
	GroupInteger<T>(this T input, int groupLength = 3)
	{ … }
}

Listing 5 shows how to invoke the extension method.

Listing 5

C#
static string IntegerToSentence<T>(T input, bool unsigned = false)
{
	var listInteger = input.GroupInteger();
	var subGroup = Convert.ToInt64(listInteger.Item2[j]).GroupInteger(1);
}

Group String from Right to Left

In this section, my goal was to split the given integers into 3 integers per group. Let's say, a user enters 98745612. My expected results are 98, 745 and 612. Usually, we write code to extract sub-string from a string from left to right, the result will end up like 987, 456 and 12. I did some Googling, but couldn't find the code that I'm looking for to copy and paste, maybe I didn’t use the correct keyword. So, I ended up writing my own and Is not that complicated.

Listing 6

C#
int inputLength = userInput.Length;
//read from right to left
            //group 3 digit from right to left
            while (inputLength > 0)
            {
                inputLength = inputLength - groupLength;

                if (inputLength < 0)
                {
                    startIndex = 0;
                    length = groupLength + inputLength;
                }
                else
                {
                    startIndex = inputLength;
                    length = groupLength;
                }

                inputGroup = userInput.Substring(startIndex, length);

                groupNumbers.Add(inputGroup);
            }

Point of Interest

You will be amazed that a problem can be solved by using various different programming languages. Some contestants used Python, Perl, C, C#, etc. Each have their own way to approach the problem. Let's face it, some of us learned lots of programming skills during our career but do we apply some or all of it to our daily task? Or do you remember the syntax when the time comes? I guess not. So, take some time to join one of the challenges when you have time. This is a good opportunity to refresh your memory and learn new programming skills through another contestant.

Conclusion

I hope someone will find this information useful and that it will make your programming job easier. If you find any bugs or disagree with the contents or want to help improve this article, please drop me a line and I'll work with you to correct it. As always, by anonymously/irresponsibly down-voting an article without providing a justification will not help the author nor the community.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
I have over 10 years of experience working with Microsoft technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification. I'm a highly motivated self-starter with an aptitude for learning new skills quickly.

Comments and Discussions

 
-- There are no messages in this forum --