# Einstein meets F# Part 2

In part 1, I described a riddle Einstein had come up with, and a proposed algorithm for programmatically finding the solution.  In this post, we will take the next steps of  writing our F# program, including defining the domain objects, creating a list of all the possibilities of homes, and begin filtering down this list to find the answer.

First I wanted to define a set of the distinct types for each of the houses properties as described in the riddle, e.g. colors, nationalities, beverages, smokes, and pets.  An enum seemed like the most natural fit:

`type ColorHouse = Red = 1 | Green = 2 | White = 3 | Yellow = 4 | Blue = 5`

This was my first conceptual change from the C# world. I had originally (unintentionally) created a discriminated union such as this…

`type ColorHouse = Red | Green | White | Yellow | Blue //discriminated union`

So what’s the difference between an enum and discriminated union?  You can read about discriminated unions here as well as some of the differences with enums here.  For our purposes we need something easy to enumerate over, which .NET provides many utilities for enumerating over enums but not discriminated unions.

Next, I defined a House type with members for each of our enum types.  This is a little verbose, and there may be more concise way to define a simple type in F# but it suits our purposes for now:

`type House(number:int, color:ColorHouse, nationality: Nationality, beverages:Beverages, smoke:Smoke, pet:Pet) =`

` member this.Number = number`

` member this.Color =` color

`member this.Nationality = `nationality

`member this.Beverages = `beverages

`member this.Smoke = `smoke

`member this.Pet = `pet

Next, we iterate through each of the available values of each property type, and create a home with a distinct set of property values.  Now we have created a set homes with all combinations of property values represented.

`let houses = [for i in [1..5] do`

for color in colors do

for nationality in nationalities do

for beverage in beverages do

for smoke in smokes do

for pet in pets do

yield new House(i, color, nationality, beverage, smoke, pet)]

Now that we have all possibilities of house values (15625!) we are going to filter out the houses that do not pass the rules applicable to a single home given to us in the riddle.  Lets create the set of functions that determine a valid home…

`let rule1(house:House) =  exnor((house.Nationality = Nationality.Brit), (house.Color = ColorHouse.Red))`

`let rule10(house:House) = exnor((house.Nationality = Nationality.German), (house.Smoke = Smoke.Prince))`

Great, now lets create a list of those rules and apply them to all the house combinations.

`let singleRuleSet = [rule1;rule2;rule3;rule4;rule5;rule6;rule7;rule8;rule9;rule10;]`

`let rulesPredicate(house:House) = singleRuleSet |> List.forall(fun rule -> rule(house))`

`let housesPassedRules = houses |> List.filter rulesPredicate`

We now have the set of homes that pass the ‘single home’ rules. For the final part of this blog series, we will create sets of  sets of homes and a list of ‘multi home’ rules, and apply this last rule filtering.   This should leave a single set of 5 homes, and reveal the answer to the riddle!

To be continued…part 3.

# 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.

# .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 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;

}

}

# Dynamically handling jQuery UI css states

I recently completed a project using jQuery and jQuery UI, and found them to both be incredible tools for creating dynamic websites.  One limitation with the jQuery UI css library was that while classes are provided for hover and focus states they are not driven by css pseudo selectors, meaning you have to dynamically add the classes yourself.  Using the jQuery live bind function this can be done with the following code snippet I wrote….

\$(function() {/* Bind  functions for handling css class to jQuery events */

\$(“.ui-state-default:not(.ui-state-disabled)”).live(“mouseover”, function() {

});

\$(“.ui-state-default:not(.ui-state-disabled)”).live(“mouseout”, function() {

\$(this).removeClass(“ui-state-hover”).removeClass(“ui-state-focus”);

});

\$(“.ui-state-default:not(.ui-state-disabled)”).live(“mousedown”, function() {

});

\$(“.ui-state-default:not(.ui-state-disabled)”).live(“mouseup”, function() {

\$(this).removeClass(“ui-state-focus”);

});

\$(“.ui-state-default:not(.ui-state-disabled)”).live(“focus”, function() {

});

\$(“.ui-state-default:not(.ui-state-disabled)”).live(“blur”, function() {

\$(this).removeClass(“ui-state-hover”);

\$(this).removeClass(“ui-state-focus”);

});

\$(“.ui-state-default:not(.ui-state-disabled)”).live(“keydown”, function() {

});

\$(“.ui-state-default:not(.ui-state-disabled)”).live(“keyup”, function() {

\$(this).removeClass(“ui-state-focus”);

});

});

Basically, you are selecting the elements on the page with the css class “ui-state-default” and add or removing the appropriate functions to change the css classes based on the triggered jQuery event.

# Duplicate title tags in ASP.NET MVC 1

Quick “bug” I found in asp.net mvc.  When you create a new asp.net mvc application the default masterpage template has a  runat=”server” tag on the header like so:

<title><asp:ContentPlaceHolder ID=”TitleContent” runat=”server” /></title>

This is fine except when you make a contentplaceholder to hold the title so each page could implement the title specific to that page like this:

<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />

When you use the contentplaceholder to add the title the runat=”server” tag will cause the asp.net engine to add an empty title tag to the head as if it doesn’t see that it was added from the MVC view causing the following output.

<title>Test Page</title>

<script src=”/Scripts/MainJavascript.js” type=”text/javascript”></script><title>