Project Euler Problem 4 in F#

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



  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.



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




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


let livesNextTo(house1:House, house2:House) =

let multiRule1(houses:List<House>) =
greenHouse.Number = whiteHouse.Number - 1

let multiRule2(houses:List<House>) =
livesNextTo(blendSmoker, catPerson)

And for the multi rules….






let finalSets : List<List<House>> =


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 finalSet = finalSets |> List.head




Download the source code for this post.

Einstein meets F# Part 2









member this.Number = number

member this.Color = color

member this.Nationality = nationality

member this.Beverages = beverages

member this.Smoke = smoke

member this.Pet = pet



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








let housesPassedRules = houses |> List.filter rulesPredicate


To be continued…part 3.

Download the source code for this post.

Einstein meets F# part 1





The Riddle

  2. In every house leaves a person of different nationality.

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.
  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.
  12. The man who smokes Blue Master drinks beer.
  13. The German smokes Prince.
  14. The Norwegian lives next to the blue house.

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;