Tag Archives: .net

Einstein meets F# part 1

Recently, I began an attempt to learn the new .NET language, F#. I had never worked with a functional programming language before, and the C# 3.0 “functional” features had piqued my interest. I began by buying the excellent Expert F# 2.0 written for the F# 2.0 spec.  It is written by Don Syme the designer and architect of F#.  Its an excellent book, which I highly recommended.

I only have two small criticisms of the book which can probably be overlooked. First, it is a little unforgiving in making sure the reader is “up to speed” when combining concepts introduced in previous chapters.  This is a book where you will want to take notes, and make sure you understand the concepts before moving on.  Secondly, it has many chapters towards the end describing the basics of the .NET framework, which may be useful to some but are also a repeat of what I see in dozens of other books in the same family, e.g. .NET, Silverlight, C#, asp.net mvc, webforms, etc.

While the book was excellent, I do my best learning by doing and not reading.  So what program should be my first in F#?

I found a blog post in my daily barrage of code forum emails that looked interesting enough to try and solve with F#.  It described an approach to programmatically solving a riddle created by Albert Einstein. The riddle is as follows:

The Riddle

  1. In a town, there are five houses, each painted with a different color.
  2. In every house leaves a person of different nationality.
  3. Each homeowner drink a different beverage, smokes a different brand of cigar, and owns a different type of pet.

The Question

Who owns the fishes?

Hints

  1. The Brit lives in a red house.
  2. The Swede keeps dogs as pets.
  3. The Dane drinks tea.
  4. The Green house is next to, and on the left of the White house.
  5. The owner of the Green house drinks coffee.
  6. The person who smokes Pall Mall rears birds.
  7. The owner of the Yellow house smokes Dunhill.
  8. The man living in the center house drinks milk.
  9. The Norwegian lives in the first house.
  10. The man who smokes Blends lives next to the one who keeps cats.
  11. The man who keeps horses lives next to the man who smokes Dunhill.
  12. The man who smokes Blue Master drinks beer.
  13. The German smokes Prince.
  14. The Norwegian lives next to the blue house.
  15. The man who smokes Blends has a neighbor who drinks water.
First, I needed to decide how I could algorithmically solve the problem.  I decided upon a naive approach, of creating a list of every combination of the given home properties (i.e., color, pet, smoke, etc.). Than applying the given rules to obtain the list of valid houses, e.g. those that passed the given rules for a single house.  Than I would create sets of houses from all the permutations of remaining homes, and filter those based on the rules that apply to more than a single house.
In my next post, we will begin defining our domain objects.

To be continued in part 2.

Download the source code for this post.

.NET collections and search times

I came across a question on stackoverflow.com on which is the fastest collection for finding if a string of equal value is contained in the collection.  It was correctly answered that a Hashset in .NET 3.5 and a Dictionary in .NET 2.0 would be the fastest collections for finding an exact string match, since they both run in O(1) time.

I was still interested in what the relative difference in times would be.  So I wrote a console application that created a list of 100K unique strings in 5 common collection types and than searched each of the collections for the 100K strings, recording the time for each collection to find them all.  Here are the results …

Trial 1: Trial 2: Trial 3:
NameValueCollection 82.1ms 78.9ms 79.7 ms
HashSet 23.8ms 24.9ms 24.3 ms
Dictionary 25.7ms 26.2ms 29.0 ms
List 1:03.985 min 1:20.637 min 1:04.39 min
Sorted List<string> w/ BinarySearch 199.9ms 210.0 ms 214.0 ms

As predicted the HashSet and Dictionary were the fastest, but is that the whole story?  What if we wanted to perform a case insensitive search, would the results be the same?  What is the performance impact of populating these collections?  How much memory do they use?

Much of the quicker lookup times of the key value based collections comes at the price of increased overhead in populating the collections as well larger memory footprint.

Prettify a list of integers in C#

In a recent project using .NET 3.5 and C# I needed to print out a long list of integers for the UI.  This is of course quite trivial, but I also wanted to make it easy to read by replacing all consecutive numbers with a hyphen.  For example a list of integers like this 1,2,3,4,5,7,8,10,11, should print out as 1-5, 7-8, 10-11.

I wrote the following extension method on the the IEnumerable<int> interface to accomplish this.  You can download it.

Update: Modified algorithm to run in O(n) instead of O(n2) time.

using System.Collections.Generic;using System.Linq;using System.Text;public static class EnumerableIntExtensions

{

public static string GetOrderedSetValues(this IEnumerable<int> list)

{

var orderedSet = list.OrderBy(x => x).Distinct().ToList();

var returnValue = new StringBuilder(orderedSet.Count * 2);

for (int currentIndex = 0; currentIndex < orderedSet.Count; currentIndex++)

{

if(IsEndOfList(orderedSet, currentIndex))

{

returnValue.Append(orderedSet[currentIndex]);

}

else if (IsBeginningOfGroup(orderedSet, currentIndex))

{

returnValue.Append(orderedSet[currentIndex]);

if (IsEndOfGroup(orderedSet, currentIndex))

{

returnValue.Append(“, “);

}

else

{

returnValue.Append(“-“);

}

}

else

{

if (IsEndOfGroup(orderedSet, currentIndex))

{

returnValue.Append(orderedSet[currentIndex]);

returnValue.Append(“, “);

}

else

{

//do nothing, ie. middle of grouping

}

}

}

return returnValue.ToString();

}

private static bool IsBeginningOfGroup(IList<int> list, int index)

{

if (index == 0) { return true; }

bool precedingExists = list[index] – 1 == list[index -1];

return !precedingExists;

}

private static bool IsEndOfGroup(IList<int> list, int index)

{

if (index == list.Count – 1) { return true; }

bool succeedingExists = list[index] + 1 == list[index + 1];

return !succeedingExists;

}

private static bool IsEndOfList(IList<int> list, int index)

{

return list.Count == index + 1;

}

}