Tag Archives: einstein

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.

Advertisements

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