Advent of Code - Year 2015, Day 02
Problem statement: http://adventofcode.com/2015/day/2
Part A
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.
Part B
Again, this requires following the provided formulas. In this case, we sort the dimensions and take the two smallest for the formula.
C#
source
Most of the code is LINQ-based, being easier to describe and read. The two interesting things of note:
Regex
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.
@"(?<l>\d+)x(?<w>\d+)x(?<h>\d+)"
The first thing to know is that \d
describes a single numerical digit (0
-9
). +
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 928c34
.
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 w
.
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.
Sorting
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.
F#
source
The F# code is very similar to the C# code. The only difference is using the F# Seq.map
and Seq.sort
instead of the LINQ .Select()
and .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.