14 May 2017

How to Setup a Fable-Elmish Project (May 1 2017)

Table of Contents

How to Setup a Fable-Elmish Project (May 1 2017)

This is a short post that details the steps needed to setup a basic project with the following tools:

  1. .NET Core and F#
  2. Fable-Elmish
  3. Working Time Travel Debugger on Firefox and Chrome.

At the end, you should have the sample Fable-Elmish project (showing navigation and counter example) running in a browser with a working time travel debugger.

These instructions are working as of 1 May 2017.

NOTE: If you are already familiar with Fable-Elmish, this post will probably not help you. However, I would greatly appreciate any tips or corrections to improve these instructions.

Setup .NET Core and F#

The first step I took was to setup .NET Core. I downloaded and installed 3 packages, in the given order.

IDE

Install the IDE of your choice. I decided to go with Visual Studio Code and Ionide.

At a minimum, install the following extensions in VS Code to take full advantage of Ionide's F# development environment. - Ionide-FAKE - Ionide-fsharp - Ionide-Paket

There are lots of additional extensions available in VS Code that can make your life easier during the development process. Feel free to experiement!

.NET Core

Install .NET Core from the Microsoft Website. - Pick the appropriate version for your environment. - I did this on a Windows 7 64-bit machine, and the x64 version worked correctly for me. - At the time that I installed it, my version of the SDK was 1.0.3.

Microsoft Build Tools

Install Microsoft Build Tools 2015 from the Microsoft Website.

F# 4.0

Install Microsoft Visual F# 4.0 Tools RTM from the Microsoft Website.

At the time that I downloaded this, F# 4.1 was available. However, I used F# 4.0 based on advice in an issue in the Ionide GitHub project.

Setup Fable-Elmish

Install yarn

Yarn is a Node.js package manager, similar to npm. Fable / Fable-Elmish are using yarn, so you will need to install it.

I already had Node and npm installed, so I installed yarn with the following command.

npm install --global yarn

If you do not have npm, then you can download a yarn installer from the Yarn Website. Please note that I'm not sure if you will need npm as well, so keep in mind that you may need to install it later.

Setup a new project with Fable-Elmish

Setting up Fable-Elmish in a way that you can use it for a new project requires a bit of CLI work. Here are the steps.

  1. Open a command prompt / shell.

  2. Install the Fable-Elmish templates. This is the command to install the templates for Fable-Elmish based on the React framework.

    dotnet new -i "Fable.Template.Elmish.React::*"
  3. Create a new Fable-Elmish project.

    dotnet new fable-elmish-react -n project-name
  4. Go to your new project directory.

    cd project-name
  5. Install your Node-based dependencies. Running yarn without parameters is equivalent to the npm install command.

    yarn
  6. When I ran the commands, I received a warning from yarn about the version of my remotedev dependency. When I looked at package.json, I saw that my dependency was at version ^0.2.7 but my devDependency was at version ^0.2.5.
    • I fixed this situation by changing the devDependency version to ^0.2.7.
  7. Restore your NuGet-based dependencies.

    dotnet restore

Setup debugging environment

Chrome

  1. Install the React Developer Tools from the Chrome Web Store.

  2. Install the Redux DevTools from the Chrome Web Store.

Firefox

  1. Install the React Developer Tools from the Mozilla Add-ons site. When installed, this add-on will be called React Devtools.

  2. Install the Redux DevTools from the Mozilla Add-ons site.

Opera, IE, Safari, etc.

I have not tried these instructions myself, so please take with a grain of salt.

  1. React Developer Tools offers a standalone version for browsers / environments other than Chrome and Firefox. You can find the installation and usage instructions on the react-devtools GitHub Website.

  2. zalmoxisus, the person who has released the Redux DevTools extensions for Chrome and Firefox, has a package called remote-redux-devtools for use with browsers / environments other than Chrome and Firefox. You can find the installation and usage instructions on the remote-redux-devtools GitHub website.

Run the sample

  1. To run the sample, go to the project directory and run the following command.

    dotnet fable npm-run start
  2. Open your browser (I recommend Chrome or Firefox) and go to http://localhost:8080/.

  3. To open the debugger:
    • If you are using Chrome or Firefox, you will see a small green icon. Clicking on it will bring up the Redux DevTools panel / window that will show state changes (if you've taken any actions in your browser).
    • If you decided to use the remote-redux-devtools, you may have you modify the default app. If it doesn't work by default, see the fable-elmish debugger GitHub Website for more details.
  4. If you want to build the project for release, run the following command.

    dotnet fable npm-run build

Next steps

At this point, the basics should be setup and the project is ready for your custom code.

If you are stuck, an excellent resource is the Fable Gitter channel, where a number of Fable and Fable-Elmish developers often hang out.

If you are not familiar with the Elm architecture, that is a good next step.

This default version also does not give you certain often-requested features, such as using Rollup instead of Webpack.

Conclusion

If you are still reading, I hope this guide has helped you setup your first Fable-Elmish project.

If you have any suggestions, tips, or corrections, please leave them as a comment below.

See you next time!

07 May 2017

AOC 2016 - Day 7

Table of Contents

AOC 2016 - Day 7

Problem statement on the Advent of Code website.

Code for this post can be found on GitHub.

Background

  • On Day 1, we located Easter Bunny headquarters.
  • On Day 2, we broke the code to use the bathroom in Easter Bunny HQ.
  • On Day 3, we helped the EBHQ's design department by removing invalid triangles from the list.
  • On Day 4, we figured out which rooms in the information kiosk are valid.
  • On Day 5, we figured out how to get past security doors by calculating the code.
  • On Day 6, we figured out how to communicate with Santa through the Easter Bunnies' jamming technology.

On Day 7, we will figure out which of the EBHQ's computers use encryption on the network.

Problem - Part 1

For Part 1, we need to find the IP addresses (aka computers) that support the TLS (transport-layer snooping) protocol.

We determine this by parsing the IP address and checking for certain patterns.

Solution - Part 1

When I read the problem description, Day 7 sounded very similar, at least in form, to the Day 4 problem.

The problem has multiple parts:

  1. Extract supernet and hypernet sequences from an IP address.
  2. Check for an ABBA pattern.
  3. Check an entire IP address.
  4. Connect the pieces.

Extract supernet and hypernet sequences from an IP address

The first part of the problem is understanding the format of the IP address. IP addresses are strings of characters alternating between being outside and inside square brackets. Here are some examples of IP addresses:

  • abba[mnop]qrst
  • abcd[bddb]xyyx[bddb]xyyx
  • ioxxoj[asdfgh]zxcvbn

This solution, just like the Day 4 solution, stretched and expanded my regular expression skills. I would like to thank Will Boyd for the Regex Storm Regex Tester. This site made it much faster and easier to quickly test a regular expression (and its expected results) against a corpus of test data.

After a number of attempts, I ended up with two sets of regular expressions.

For supernet strings (whose proper name I did not know until Part 2), I used the following strategy:

  • Remove all text between square brackets [].
  • Break the resulting compound string into a list of strings.
  let outerStrings =
    Regex.Replace (str, @"\[\w+\]", " ")
    |> fun s -> s.Split ([|' '|])

For hypernet strings, I used the following strategy:

  • Extract all text that is between square brackets [].
  • Remove the brackets.
  let hypernetStrings =
    Regex.Matches (str, @"\[\w+\]")
    |> Seq.cast
    |> Seq.map (fun (m:Match) -> Regex.Match(m.Value, @"\w+"))
    |> Seq.cast<Match>
    |> Seq.map (fun x -> x.Value)

Check for an ABBA pattern

An ABBA (Autonomous Bridge Bypass Annotation) pattern is a palindrome of exactly 4 characters within a string of length 4 or more.

let isABBA (str:string) =
  str
  |> Seq.windowed 4
  |> Seq.exists (fun s -> s.[0] = s.[3] && s.[1] = s.[2] && s.[0] <> s.[1])

Check an entire IP address

For Part 1, we have two primary requirements.

  • The supernet sequences must contain at least one ABBA.
  • The hypernet sequences must not contain any ABBAs.

The check for this is a one-liner.

  (Seq.exists isABBA outerStrings) && (Seq.exists isABBA hypernetStrings |> not)

Connect the pieces

The final function that puts it all together is responsible for the following.

  • Read the list of IP addresses.
  • Find the addresses that support TLS.
let day7part1 filename =
  File.ReadAllLines filename
  |> Seq.filter supportsTLS
  |> Seq.length

When you run this function, you get 105, which is the correct number of IP addresses that support TLS.

Problem - Part 2

In Part 2, we have to determine which IP addresses support the SSL (super-secret listening) protocol.

The problem for Part 2 keeps the concept of supernet and hypernet sequences, but it changes the checks we need to perform on them. Instead of checking for ABBAs, we have to now check for ABAs and their dependent BABs.

Solution - Part 2

Part 2 introduces two new types of patterns in IP addresses:

  1. ABA
    • Area-Broadcast Accessor
    • Follows the pattern of 'First char', 'Second char', 'First char'
    • E.g. aba, xyx, pup
  2. BAB
    • Byte Allocation Block
    • Contains the same characters as an ABA, but is reversed positions.
    • E.g. bab, yxy, upu

The requirements are as follows.

  1. There must be at least one ABA in the supernet sequences.
  2. There must be at least one BAB in the hypernet sequences.

My strategy for the Part 2 solution has slightly different steps.

  1. Extract supernet and hypernet sequences from an IP address.
  2. Check if a supernet sequence has at least one ABA.
  3. Check if a hypernet sequence has at least one BAB.
  4. Check a single IP address.
  5. Connect the pieces.

Extract supernet and hypernet sequences from an IP address

Extracting the supernet and hypernet sequences from an IP address follows exactly the same logic as the Part 1 problem. I extracted this code into two new functions and refactored the Part 1 code to use these new functions.

/// Extract supernet sequences from an IP address.
let supernetSeq ip =
  Regex.Replace (ip, @"\[\w+\]", " ")
  |> fun s -> s.Split ([|' '|])

/// Extract hypernet sequences from an IP address.
let hypernetSeq ip =
  Regex.Matches (ip, @"\[\w+\]")
  |> Seq.cast<Match>
  |> Seq.map (fun m -> Regex.Match(m.Value, @"\w+"))
  |> Seq.cast<Match>
  |> Seq.map (fun x -> x.Value)

Check if a supernet sequence has at least one ABA

The function hasABA takes a string of any length and tries to find at least one 3-character substring which matches the ABA pattern, which is:

  • The first and third character must be the same.
  • The first and second character must be different.
let hasABA (str:string) =
  str
  |> Seq.windowed 3
  |> Seq.exists (fun x -> x.[0] = x.[2] && x.[0] <> x.[1])

Check if a hypernet sequence has at least one BAB

To check if a hypernet sequence contains a BAB, I decided to use the Set collection. My overall strategy is as follows.

  1. Get all ABAs from the supernet sequences.
  2. Flip the ABAs (i.e. turn them into BABs).
  3. Get all the BABs from the hypernet sequences.
  4. Check if the Sets intersect.

First (and third), here is the code to get ABAs (or BABs) from IP addresses.

let getABAs (str:string) =
  str
  |> Seq.windowed 3
  |> Seq.map (System.String)
  |> Seq.filter hasABA

Second, here is the code to flip an ABA.

let flipABA (str:string) = sprintf "%c%c%c" str.[1] str.[0] str.[1]

Finally, I connected these pieces in the hasBAB function.

let hasBAB abas hnStr =
  let babs =
    hnStr
    |> getABAs
    |> Set.ofSeq
  abas
  |> Set.ofSeq
  |> Set.map flipABA
  |> Set.intersect babs
  |> (Set.isEmpty >> not)

Check a single IP address

The function supportsSSL is responsible for ensuring that the supernet sequences contains at least one ABA and that the hypernet sequences contain at least one BAB.

let supportsSSL line =
  let abas =
    supernetSeq line
    |> Seq.collect getABAs
  (supernetSeq line |> Seq.exists hasABA)
  && (hypernetSeq line |> Seq.exists (hasBAB abas))

Connect the pieces

The last function, day7part2, is responsible for linking the input file to supportsSSL and for calculating the final answer (i.e. the number of IP addresses that support SSL).

let day7part2 filename =
  File.ReadAllLines filename
  |> Seq.filter supportsSSL
  |> Seq.length

Lessons learned

Thanks to Day 7 being a relatively simple problem, my goal here was to expand my knowledge of testing.

  1. "If at first you don't succeed, try, try again." I once again worked on making Expecto and FsCheck work together.
    • As with Day 6, I did not end up using FsCheck - however, this was mainly because I could not get a good generator written for IP addresses.
    • In the end, I used the provided tests to ensure that my code is working correctly.
    • Since the time that I finished Day 7, I actually rewrote the solution to Day 2 using a variety of graph data structures (and corresponding algorithms) and used FsCheck extensively there and with the updated MD5 testing I did. I feel a little more comfortable with FsCheck now, though I am still not completely clear on how to generate restricted data (e.g. positive ints) other than through rather rudimentary methods.

My goal with Day 8 (and beyond) is to start using new platforms (specifically, Fable, Elmish, Suave, etc.). I'm extremely excited to be doing this.

See you next time!

03 May 2017

AOC 2016 - Day 6

Table of Contents

AOC 2016 - Day 6

Problem Statement on Advent of Code website.

Code for this post can be found on GitHub.

Background

  • On Day 1, we located Easter Bunny headquarters.
  • On Day 2, we broke the code to use the bathroom in Easter Bunny HQ.
  • On Day 3, we helped the EBs' design department by removing invalid triangles from the list.
  • On Day 4, we figured out which rooms in the information kiosk are valid.
  • On Day 5, we figured out how to get past security doors by calculating the code.

On Day 6, we will figure out how to communicate with Santa through the Easter Bunnies' jamming technology.

Problem - Part 1

For Part 1, we are given a list of garbled versions of a message that we sent to Santa. Per the protocol, we switched to a simple repetition code to get the message through.

Our goal is to figure out the original message.

Solution - Part 1

Compared to the rather more difficult problem on Day 5, the solution to Part 1 is relatively simple.

The problem states that we have to find the most frequent character in each column and, by stringing these characters together, we will derive the original message.

To solve this problem, I performed three explicit steps.

  1. Calculate the length of the longest string from the list of garbled messages.
    • I did not want to assume that all strings are the same length.
  2. Find the most frequent character for each position from the subset of strings that are long enough for that position.
  3. Combine the characters to construct the final answer.

Calculate length of the longest garbled message

To calculate the length of the longest garbled message, I used a simple function to take the list, map each string message to its length, and then get the largest number.

let longestLength list =
  list
  |> Seq.map (String.length)
  |> Seq.max

Find the most frequent character in a given position

To find the most frequent character in a given position, I performed the following steps.

  1. Filter the list of strings and only retain those strings that are long enough to have a character in the desired position.
  2. Count the number of occurrences of each character.
  3. Sort the list so that the character with the highest number of occurrences is at the head of the list.
  4. Return the character.
let mostFreqentCharAt pos list =
  list
  |> Seq.filter (fun line -> String.length line >= (pos + 1))
  |> Seq.map (Seq.item pos)
  |> Seq.countBy id
  |> Seq.sortByDescending snd
  |> Seq.head
  |> fst

Collect the most frequent characters in each position

The final collection function is responsible for the following steps.

  1. Read the garbled messages from a file.
  2. Find the most frequent character in each position, based on the length of the longest message.
  3. Concatenate the MFCs to get the original message.
let day6part1 filename =
  let lines = File.ReadAllLines filename
  seq {
    for i = 0 to (longestLength lines - 1) do
      yield (mostFreqentCharAt i lines |> string)
  }
  |> Seq.reduce (+)

If you run the above function, you will get tsreykjj, which is the correct answer.

Problem - Part 2

The problem statement for Part 2 only makes a slight change to the problem in Part 1. Instead of the most frequent character, we had agreed to use a modified repetition code when communicating with Santa and actually want the least frequent character in each position.

Unfortunately, I chose not to make the "frequency" function a parameter to the day6part1 function in the original implementation. Because of this, I had two options:

  1. Go back and make the frequency function a parameter so that I can re-use the function.
  2. Implement another version of the function using the new leastFreqentCharAt function.

I chose to go with option 2 for expediency sake. This is because I was experimenting with two other things for the Day 6 project.

  1. Using a F# project and .fs files instead of .fsx files
  2. Using the Expecto testing framework

Solution - Part 2

For the Part 2 solution, I kept the function that finds the longest string in the list of garbled messages. I had to reimplement two functions.

  1. A function to find the least frequent character in a given position.
  2. The collection function to derive the original message.

Find the least frequent character in a given position

This function is very similar to Part 1's implementation, except that my sort now puts items in ascending instead of descending order.

let leastFreqentCharAt pos list =
  list
  |> Seq.filter (fun line -> String.length line >= (pos + 1))
  |> Seq.map (Seq.item pos)
  |> Seq.countBy id
  |> Seq.sortBy snd
  |> Seq.head
  |> fst

The F# library functions for collections truly make it easy to perform the types of transformations requested in this problem.

Collect the least-frequent characters in each position

This collection function is identical in all ways to the Part 1 solution except for the frequency function that it uses.

let day6part2 filename =
  let lines = File.ReadAllLines filename
  seq {
    for i = 0 to (longestLength lines - 1) do
      yield (leastFreqentCharAt i lines |> string)
  }
  |> Seq.reduce (+)

When you run this function, you get hnfbujie which is, in fact, the correct answer.

Considerations for Day 6

When it came to the Day 6 problem, I wanted to try some new things to continue the learning process with F#. To that end, I incorporated two new pieces into my solution.

  1. Writing the code in .fs files as part of a "proper" project that compiles to an executable.
  2. Writing tests using the Expecto testing library.

Using a F# project template

For the most part, using a F# project template and .fs files was seamless. I was already familiar with Paket from previous projects, so the only difference was that I had to invoke my build script when I wanted to test my code.

However, I ran into an extremely frustrating bug that almost caused me to give up on Ionide. For whatever reason, Ionide is unable to understand references to DLLs in FsProj files and, thus, is unable to provide any Intellisense support for downloaded NuGet packages. This problem was so frustrating that I actually downloaded, installed, and used Visual Studio 2017 Community Edition to finish off the Day 6 implementation (which is why the indentation scheme in the source files is different for Day 6 compared to all previous solutions).

Based on some searching and reading, I am not the only person having this problem (1, 2, 3, etc.). I can only hope that the authors are able to resolve the issue soon. Until this problem is fixed, I have stopped using F# projects and .fs files and have gone back to using F# scripts (.fsx files).

Using a testing framework

For Day 6, I did quite a bit of research to find a testing framework that I would be able to use with my solution. I specifically did this with the Day 6 problem because the solutions were relatively simple compared to previous Days.

Here is a list of the frameworks that I considered.

  1. Expecto
  2. Fuchu
  3. xUnit.net
  4. NUnit
  5. FsCheck, without a framework

In the end, I chose to go with Expecto. This was a rather difficult transition for me because I bit off a little more than I could chew - I tried to use both Expecto and FsCheck for the Day 6 problem. In hindsight, this was a terrible idea for my first-time use of Expecto. Long story short, I was unable to get Expecto+FsCheck to work in a reasonable amount of time and settled for implementing the AOC-provided tests in Expecto. My frustration stemmed, in no small part, from a fundamental misunderstanding of FsCheck's purpose and capabilities.

Despite the large amount of frustration I felt while trying to get FsCheck to work, I was able to get basic testing working and even built a simple driver to either run tests (default) or calculate the Part 1 / Part 2 answer.

[<EntryPoint>]
let main argv =
  match argv with
  | [| first |] when first = "p1" ->
    let ans = Solution.day6part1 @"..\SixMain\SixMain\puzzle_input.txt"
    printfn "Day 6 Part 1: %A" ans
    0
  | [| first |] when first = "p2" ->
    let ans = Solution.day6part2 @"..\SixMain\SixMain\puzzle_input.txt"
    printfn "Day 6 Part 2: %A" ans
    0
  | _ -> Tests.runTestsInAssembly defaultConfig argv

My actual tests were also simple and encoded only the AOC-provided tests and results. Here is the Part 1 test.

[<Tests>]
let testsPart1 =
  testList "part1"
    [ testCase "easter" <| fun _ ->
        let answer = "easter"
        let funcAns = Solution.day6part1 @"..\SixMain\SixMain\test_input1.txt"
        Expect.isTrue (answer = funcAns) @"test input answer should be 'easter'" ]

And here is the Part 2 test.

[<Tests>]
let testsPart2 =
  testList "part2"
    [ testCase "advent" <| fun _ ->
        let answer = "advent"
        let funcAns = Solution.day6part2 @"..\SixMain\SixMain\test_input1.txt"
        Expect.isTrue (answer = funcAns) @"test input answer should be 'advent'" ]

Lessons learned

While not strictly F#-related, I learned a few lessons from this exercise.

  1. When incorporating new frameworks, take it one step at a time. It's better to integrate one framework and become comfortable with it before trying to add the next one.
    • Trying to do Expecto+FsCheck while being unfamiliar with both frameworks (and, in FsCheck's case, being unfamiliar with its purpose and limitations) was simply an exercise in frustration.
  2. When dealing with tooling issues, ask for help early and often.
    • When I first encountered the Intellisense issues in Ionide, I thought I had done something wrong (esp. since all GitHub issues I found at first were closed).
    • However, it turns out that people are still experiencing these issues.

See you next time!

29 April 2017

AOC 2016 - Day 5

Table of Contents

AOC 2016 - Day 5

Problem statement on Advent of Code website.

Code for this post can be found on GitHub.

Background

  • On Day 1, we located Easter Bunny headquarters.
  • On Day 2, we broke the code to use the bathroom in Easter Bunny HQ.
  • On Day 3, we helped the EBs' design department by removing invalid triangles from the list.
  • On Day 4, we figured out which rooms in the information kiosk are valid.

On Day 5, we will figure out how to get past security doors by calculating the code.

Problem - Part 1

For Part 1, we are given two pieces of information.

  1. The door ID
  2. An increasing integer index, starting at 0.

For each MD5 hash that starts with 00000 (five 0's), the 6th digit indicates the next character of the password. If we find eight hashes that start with five 0's, that provides the password.

Solution - Part 1

My strategy to solve this problem was two-fold.

  1. Write an MD5 algorithm in F#.
    1. I outlined my solution for a functional MD5 algorithm in F# in a previous blog post.
  2. Write a function to collect the required hashes and construct the final answer.

The vast majority of the functionality for this solution is in the MD5 algorithm, which I won't describe here again.

Collection function

Once I had an MD5 algorithm, I used the Seq module and its library functions to collect the required hashes and calculate the door password.

The strategy for the function is simple.

  1. Start by producing indices starting at 0.
  2. Map all the strings to hashes.
  3. Remove all hashes that don't match the criteria (i.e. hashes that don't start with 00000).
  4. Once we have eight hashes, stop producing indices and get the final answer.
let day5part1input = "cxdnnyjw"

let day5part1criteria = "00000"

let day5part1 input crit (md5sum:string -> string) =
  Seq.initInfinite (fun i -> input + string i)
  |> Seq.map md5sum
  |> Seq.filter (fun m -> m.StartsWith crit)
  |> Seq.take 8
  |> Seq.map (Seq.item 5 >> string)
  |> Seq.reduce ( + )

When I ran the function, I got F77A0E6E, which is the correct answer.

Problem - Part 2

The problem statement for Part 2 still uses the MD5 function, but adds a twist to the password computation. We still have the same information from the problem.

  1. The door ID
  2. An increasing integer index, starting at 0.

We are still only interested in hashes that start with five 0's, i.e. 00000. The sixth character of the hash now indicates the position in the solution and the seventh character is what goes into that position.

If we get multiple hashes that meet the criteria and indicate the same position, all but the first match are ignored. Hashes that meet the criteria but indicate an invalid position, i.e. anything other than 0-7, are also ignored.

Solution - Part 2

To solve Part 2, I wanted to use a similar approach to Part 1. However, I needed to way to determine when the algorithm had collected enough values to form a complete answer.

My overall strategy was as follows.

  1. Start by producing indices starting at 0.
  2. Map all the strings to hashes.
  3. Remove all hashes that don't match the criteria.
  4. Once I have a character for each position of the answer, stop producing indices and get the final answer.

Storing the pieces of the answer

I chose to use a Dictionary<int, string> collection to hold the values that would form the answer. The keys represent the position in the answer and the values are the single-character strings that, when concatenated, would form the answer.

First, I created a value that would hold the relevant pieces.

let answer = Dictionary<int, string> 8

Second, I created an add function that would only add values to the Dictionary if a value for the key was not already present.

let add (d:Dictionary<_,_>) kv =
  if not <| d.ContainsKey(fst kv) then
    d.Add(fst kv, snd kv)
  else ()

Third, I created a notComplete function to check whether I had collected enough values for an answer.

let notComplete (d:Dictionary<_,_>) = d.Count < 8

Collecting the pieces of the answer

Once I had decided on a storage strategy, I wrote a function to add values to the Dictionary until I had enough to get an answer.

The overall strategy for this part of the logic depends on the Seq.takeWhile function. This function will terminate the infinite sequence generator once the Dictionary is "full".

Seq.initInfinite (fun i -> input + string i)
|> Seq.map md5sum
|> Seq.filter
  (fun m ->
    (m.StartsWith crit)
      && (m.[5] = '0' || m.[5] = '1' || m.[5] = '2' || m.[5] = '3'
      || m.[5] = '4' || m.[5] = '5' || m.[5] = '6' || m.[5] = '7'))
|> Seq.map (fun m -> m.[5] |> string |> System.Int32.Parse, m.[6] |> string)
|> Seq.takeWhile (fun _ -> notComplete answer)
|> Seq.iter (fun m -> add answer m)

Producing the answer

As the last step, I pulled the values from the Dictionary and concatenated the strings to get the final answer.

I chose to explicitly pull the values based on key lookups because, while there are library functions to get a collection of the values, I did not see any guarantees about the order that the items would be in.

[
  for i in 0 .. 7 do
    yield answer.[i]
]
|> List.reduce ( + )

When I ran this function, I got back 999828EC which is, in fact, the correct answer.

Some side notes

Mutable vs. Immutable data structures

As you may have noticed, I am using a mutable data structure to store the needed values for the Part 2 solution. At the time, I struggled to find a "pure" functional way of solving the problem but couldn't come up with something off hand (and, to tell you the truth, I didn't try too hard since I had just finished the MD5 algorithm and wanted to be done with this problem).

However, the Part 2 algorithm can easily be rewritten using a tail-recursive function and immutable data structures. The tail-recursive part is important because, while I don't know how many hashes the algorithm has to go through, I do know that even the OOTB MD5 algorithm takes over 2 minutes to calculate the answer (and my functional MD5 algorithm takes over 7 minutes). From that, I assume that the stack would get very deep if the function was not tail-recursive.

Seq vs. ParallelSeq

In order to speed up the calculation, I attempted to use the ParallelSeq library to take advantage of my CPU's multiple cores. Using the ParallelSeq library did speed up my calculations considerably.

However, one thing I learned is that the ParallelSeq library does not take care of putting the calculated values back in their original order. Instead, it is the client's responsibility to track the order of values (if that is important - and in this case it was).

As an example, when I used the ParallelSeq library, the system produced C9E29889 as the answer for Part 2. However, the correct answer for Part 2 is 999828EC, which are the same characters but in the correct order.

In the end, I removed ParallelSeq from this solution but it is a library that I intend to investigate in the future.

Lessons learned

Here are the lessons I learned from this exercise.

  1. Take the time to implement a solution the way you want, so that you do not later have regrets about it. In this instance, I regret choosing a mutable data structure and imperative algorithm to solve Part 2 and it's something I hope to rectify in the near future.
  2. Just as when I implemented the MD5 algorithm in F#, it is critical to be extra vigilant when reading code. Much more so than any other technique, reading and understanding code is the fastest way to find and fix most bugs.

See you next time!

PS: Solution - Part 2 (Pure functional implementation)

After I wrote this blog post, but before posting it, I decided to rewrite the Part 2 solution using immutable data structures.

Rewriting the function was quite simple, and relied on the following strategy.

  1. Define a completion check to terminate the recursive function.
  2. Define a tail-recursive function to calculate the 8 characters of the answer.
  3. Combine the 8 characters to form the final answer.

Here is the code for the pure functional implementation of Part 2, broken into 3 chunks.

let day5part2alt input crit (md5sum : string -> string) =
  let complete l = l |> List.filter ((=) "") |> List.isEmpty

  let rec collector i acc =
    if complete acc then acc
    else
      let m = md5sum (input + string i)
      if (m.StartsWith crit) then
        match m.[5] with
        | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' ->
          List.mapi (fun idx elt ->
            if elt = "" && idx = (m.[5] |> string |> System.Int32.Parse) then
              string m.[6]
            else elt) acc
          |> collector (i + 1)
        | _ -> collector (i + 1) acc
      else collector (i + 1) acc

  [ ""; ""; ""; ""; ""; ""; ""; "" ]
  |> collector 0
  |> List.reduce (+)

Running this function provides the same answer as above, i.e. 999828EC.

Performance comparison with day5part2

I compared day5part2 and day5part2alt to see whether my new implementation matches up to the previous one.

On average, I received the following results.

day5part2 vs. day5part2alt, raw numbers.
Function Real CPU Gen0 Gen1 Gen2

day5part2

174.758

174.689

21623

18

2

day5part2alt

166.528

166.437

20590

17

1

And here are the same results, converted to percentages.

day5part2 vs. day5part2alt, percentages.
Function Real CPU Gen0 Gen1 Gen2

day5part2

105%

105%

105%

106%

200%

day5part2alt

100%

100%

100%

100%

100%

Ignoring the Gen2 result, the mutable version is actually 5% worse across the board, in both processing time and increased garbage collection. It pays to be immutable.

See you next time!