Revisiting “99 Problems” in C#: Part 2

As mentioned I’ve dusted off my old github repository on the 99 problems and have had a look over them with a more experienced eye. Honestly, not sure I’d change anything mainly due to problems 1 to 8 are very simple problems (wont waste your time repeating them).

Now after a 2 year hiatus, I’m looking at problems 9 to 12. Things don’t get interesting until problem 11. For this the problem requires that a single list is returning multiple types of objects, either a single char or a tuple of int/char.  I went for the obvious option of a List<object> approach, which certainly lets me get the result I need. But, it’s ugly and if I ever had to use a List<object> in production code I’d hope the code reviewer would tut loudly before handing out a severe beating. But… the question specifically states a List[Any]  (Scala lingo for List<object>), so will leave it as that for now. In reality I’d probably leave it as a list of Tuples or come up with a common interface then have 2 classes implement it. (one for single chars, the other containing quantities).

Problem 12 had a single point of interest, which was if I have a character/object and a quantity associated, how do I “multiply” out an object that isn’t a number?

ie I have 3,’a’  how do I generate a list of ‘a’,’a’,’a’ ?

Then I remembered the lovely Enumerable class (highly underused, at least by me). Specifically the Enumerable.Range() method, which I only ever really use if I need a list of numbers generated easily. But of course I didn’t need to emit the number being generated but merely “something”. So with the simple little line:

List<char> expandedList =  (Enumerable.Range(0, myTuple.Item1).Select( n => myTuple.Item2)).ToList<char>();

It takes in a tuple (int,char) and generates a list of chars with the appropriate content. Very nice and easy.

All code has been updated here


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s