Category Archives: .NET

Project Euler Problem 4 in F#

In the continuing series of solving Project Euler problems with F#, here is problem 4 and my solution:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 ×99.

Find the largest palindrome made from the product of two 3-digit numbers.

  1. Create the set of all products of two 3-digit numbers.
  2. Filter the values that are palindromes.
  3. Find the max of the palindrome values.
open System

let problem4 =
    let reverseNumber value = Convert.ToInt32(new string(Array.rev (value.ToString().ToCharArray())))
    [for i in [100..999] do
        for j in [100..999] do yield i * j]
            |> Seq.filter (fun x -> x = reverseNumber(x)) |> Seq.max

Download the source code with unit tests.

Project Euler in F#, Problems 1 and 2

I recently stumbled across the Project Euler website. From wikipedia: “Project Euler (named after Leonhard Euler) is a website dedicated to a series of computational problems intended to be solved with computer programs”.

I thought this would be a good opportunity to continue working with F# and have some material for writing more blog articles.

Problem 1 is very straight forward.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

I went with the most logical algorithm I could think of.

  1. Enumerate though each of the numbers 1-999.
  2. Filter the values that are multiples of either 3 or 5.
  3. Add up the resulting values.

The resulting F# code is quite elegant:

let problem1 = 
    [1..999] |> Seq.filter (fun i -> i % 3 = 0 || i % 5 = 0) |> Seq.sum

After looking at other algorithms people had used, there are more efficient methods using summations. But not bad for my first solution. On to problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Again, there is a pretty obvious solution here.

  1. Generate the Fibonacci sequence up to 4 million.
  2. Filter the values that are even.
  3. Add up the resulting values.

The resulting F# code:

let Problem2 =
    Seq.unfold (fun state ->
        if (snd state > 4000000) then None
        else Some(fst state + snd state, (snd state, fst state + snd state))) (1,1)
            |> Seq.filter (fun x -> x % 2 = 0) |> Seq.sum

Again, a more efficient solution can be found but this is at least semantically easy to follow.

I’m planning on continuing this series of blog articles with a problem or 2 for each entry, and seeing how many of the problems I can get through.  I’ll also provide the source code.   If you’re interested in more in this series stay tuned!

Einstein meet F#, part 3

If you read the previous two blog posts we started to solve a riddle Einstein created, using the F# language. In this last post, we’ll finish the solution by defining the set of rules for the remaining set of houses, and hopefully find the answer to the riddle.

let livesNextTo(house1:House, house2:House) =
house1.Number = house2.Number - 1 || house1.Number = house2.Number + 1

let multiRule1(houses:List<House>) =
let greenHouse = houses |> List.find (fun h -> h.Color = ColorHouse.Green)
let whiteHouse = houses |> List.find (fun h -> h.Color = ColorHouse.White)
greenHouse.Number = whiteHouse.Number - 1

let multiRule2(houses:List<House>) =
let blendSmoker = houses |> List.find (fun h -> h.Smoke = Smoke.Blends)
let catPerson = houses |> List.find (fun h -> h.Pet = Pet.Cats)
livesNextTo(blendSmoker, catPerson)

And for the multi rules….

let multiRules = [multiRule1;multiRule2;multiRule3;multiRule4;multiRule5;]

let multiRulesPredicate(houses:List<House>) = multiRules |> List.forall(fun rule -> rule(houses))

Next we are going to group the houses by the position they have been assigned.

let groupedHouses = housesPassedRules |> Seq.groupBy (fun (house:House) -> house.Number) |> Seq.toList

Now we just need to iterate through the values of each group, which will give us a set that correctly describes the index of each house. Now we just need to apply our filtering rules that apply to the sets of houses, and only a single set should be remaining.

let finalSets : List<List<House>> =

[for g1 in snd(groupedHouses.[0]) do

for g2 in snd(groupedHouses.[1]) do

for g3 in snd(groupedHouses.[2]) do

for g4 in snd(groupedHouses.[3]) do

for g5 in snd(groupedHouses.[4]) do

let houseGroup = [g1;g2;g3;g4;g5;]

if validHouseSet(houseGroup) && multiRulesPredicate(houseGroup) then yield houseGroup]

Finally, we’ll make sure we’ve only have a single set and print out the answer to the riddle with the house number of the fish.

let answerCheck = if finalSets.Length <> 1 then raise (new Exception("Answer not found."))

let finalSet = finalSets |> List.head

let fishHouse = finalSet |> List.find (fun house -> house.Pet = Pet.Fishes)

printf "%s" ("Fish is owned by: House:" ^ fishHouse.Number.ToString())

This problem was a great introduction to learning some of the concepts of functional programming as well as the features of the F#.  In another blog series I’ll be taking a look at some of the distinguishing language  features F# has compared to C# and other .NET languages.

Download the source code for this post.

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.

Download the source code for this post.

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#, 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?


  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 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))




else if (IsBeginningOfGroup(orderedSet, currentIndex))



if (IsEndOfGroup(orderedSet, currentIndex))


returnValue.Append(“, “);









if (IsEndOfGroup(orderedSet, currentIndex))



returnValue.Append(“, “);




//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;