Problem statement: http://adventofcode.com/2015/day/2
Solving this problem is relatively straight-forward: with a for-loop, use the math formulas provided for each record in the input, and sum the results. The biggest difficulty is in identifying the face with the smallest area. We do this by calculating the area of each face and then sorting faces.
Again, this requires following the provided formulas. In this case, we sort the dimensions and take the two smallest for the formula.
Most of the code is LINQ-based, being easier to describe and read. The two interesting things of note:
Using a regex to split the input text. Technically, this text is easy to parse, and could be done using
String.Split(), but a lot of the later problems will be using regex, so I'll use it here to start explaining the regex definition and how we use it.
The first thing to know is that
\d describes a single numerical digit (
+ says that we want one or more of whatever precedes it. Putting the two together (
\d+) says that we want one or more digits (and only digits) together, or an integer. This would match
0234, but not match
012 34 or
The parentheses describe "groups", which have two goals: collect multiple regex instructions together and treat them as a single instruction, or identify something that I want to extract from the regex in some way. In our case, we are identifying three sets of numbers that we want from the regex, each separated by a
x that we don't care about.
One last thing to explain about this particular regex is that we can name a group that we want to extract from the regex. This is done using the
?<w> syntax, which tells the regex that I want to identify this group later using the name
Putting this together, I am saying here that I want three numbers, separated by
x's which I will ignore, each identified by name for later use. If you read the code, you will see that I pull them out of the regex after matching by using the name of each group.
Once we have the three dimensions split out from the input, we need to know the smallest two dimensions for Part B. The easiest way to do that is to put them in an array and do an
.OrderBy() on the array, which will sort them. This means that
boxes is of type
List<int>, i.e. it is a collection of records, each record is a sorted array of integers, or dimensions. This technique is also used in Part A to handle getting the smallest face of each box.
The F# code is very similar to the C# code. The only difference is using the F#
Seq.sort instead of the LINQ
.OrderBy(). Conceptually, the problem statement is very linear and functional description of data transformation and summation will look almost the same between F# sequences and .NET enumerables using LINQ.