99 Problems part 3

I’ve finally got around to doing some more of the fun (??) “99 Problems”. I’m using the Scala version of the problems but am solving them in C#.

Problems 13 through to 17 are now done. All fairly simple (probably due to my naive solutions).

Problem 13 was of particular interest with the problem requiring some run length encoding to be done. The problem stated is, given a list of ‘a’,’a’,’a’,’a’,’b’,’c’,’c’,’a’,’a’,’d’,’e’,’e’,’e’,’e’  calling the solution should result in an answer of 4:’a’, 1:’b’, 2:’c’, 1:’d’, 4:’e’  (ie the # of times the letter appears contiguously.

Unless the LINQ solution is obvious to me, I prefer to code up a naive foreach/while answer, confirm I understand the problem then “LINQ-ify” it. (I’ve found that so far most of the 99 problems are better solved with LINQ). My naive solution was:

 

var res = new List<Tuple<int, char>>();

var count = 0;
char ch = ' ';

foreach (var i in l)
{
if (i != ch)
{
if (ch == ' ')
{
ch = i;
count = 1;
}
else
{

res.Add(new Tuple<int, char>(count, ch));
ch = i;
count = 1;
}
}
else
{
count++;
}

}
res.Add( new Tuple<int, char>(count,ch));

Yes, it could be shortened but you get the idea. Loop through, keeping track of last char etc. Nothing earth shattering here. Once I’d completed this version I tried for ages to come up with something that was shorter and LINQ based. One thing I did NOT want to do though is use LINQ but end up with (to me) unreadable/confusing code.

Simply, I could not. If anyone else can, I’d be interested in hearing about it.

btw, looking on StackOverflow I found an answer by Jon Skeet where he basically did the same as I did (but more elegantly). So am thinking maybe there is no neat LINQ way?

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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