Question Seems like this time we are tasked with optimizing the elves' cleaning tasks! those elves can improve their lists… The cleaning tasks are assigned to each pair of elves, for example:
|
|
For the first few pairs, this list means:
- Within the first pair of Elves, the first Elf was assigned sections 2-4 (sections 2, 3, and 4), while the second Elf was assigned sections 6-8 (sections 6, 7, 8).
- The Elves in the second pair were each assigned two sections.
As always, let’s start with parsing our list of assignments to something we can work with
Parsing
First, let’s decide what we would like our output to look like.
we can create a struct that represents each pair task but that seems a bit redundant, let’s keep it simple and create something like
[[st1, et1, st2, et2] , ... ]
where st1 and et1 is the first elf range of sections and st2 and et2 are the second elf range.
We will call a range of sections a “task” from now on.
To get that we can go with splitting on various delimiters but today I finally had an excuse to use a Regex in go.
We will create a regex, containing capture groups for each t
and use
FindStringSubmatch to iterate over the resulting matches.
|
|
Its worth noting that the first match is the entire string we are passing and that’s why we are skipping it when looping over the results
range match[1:]
Part 1
The elves are really smart and noticed that some tasks entirely overlap with their partner tasks. We are tasked with finding and counting those overlaps.
Let’s draw this out so it will be a bit clearer
|
|
From the above, we can say that if one of the elves' starting tasks is greater or equal to the other elf starting task AND the final task is smaller or equal, then the assignment is contained. We now write a solution to part 1
|
|
If you know a better way to take those values from
pairAssignmentRange
let me know in the comment section
Part 2
We are asked to count overlapping tasks of any kind meaning its enough that we will have one overlapping “section” in our range for it to count as an overlap What does that mean in code? it means that we are looking for tasks that are ending inside the range of the other task. For example
|
|
These tasks overlap over “section” 7. We can now write our part 2 solution as follows
|
|
The only thing we changed was the if
statement to look at the ending task “section”
To sum things up, each day I feel more and more confident with Go, and the task’s code starts flowing.
I think that one of Go’s upsides is that the language is fairly small without any fancy concepts so the learning curve is not that long or hard.
You can find the complete code here Thanks for reading!
This post is number 5 of a 13 posts series > Learning Go.