AOC18: The Sum of Its Parts
Advent of Code 2018 Day 7
It’s that time of year again, Christmas is around the corner and Eric Wastl has gifted us with another set of Advent of Code puzzles.
Welcome to Advent Of Code 2018. You can read Part 1 of this series Here or see all the parts of this series Here.
Part 1
Day 7 gives us a list of tasks that must be completed before other tasks. Our goal is to find the correct order to process the tasks. As always, we’ll need to begin with reading in our input file.
|
|
We’ll want a new struct to hold the information for our task. We’ll call this struct Task, and it will contain the name of the step and a list of prerequisite steps.
|
|
Next we’ll need to loop through our list of tasks, creating our steps mapped by name and appending any prerequisites to the Prereq field.
|
|
Next we’ll need a couple of helper functions. The first, is a simple contains function to determine if a string slice contains a specified string.
|
|
The next function will give us the steps that have either no prerequisites, or prerequisites that have already been completed. We can use these functions with a loop to determine the next task to complete.
|
|
Now that we can determine available tasks, we’ll loop through finding all available tasks, and completing the first on the list alphabetically until there are no more available tasks. This gives us the sequence of tasks for the answer to our first part.
|
|
Part 2
For part 2, things get a little more complicated. Instead of processing tasks single-threaded, we now have 5 workers, and instead of instantly completing tasks, the tasks have a processing time of 60 seconds + the value of the letter from 1 to 26. First we’ll setup a struct for our Worker that will contain the current operation, as well as the remaining time on the operation.
|
|
We can simulate the processing by setting up a pool of 5 workers, and letting them process the tasks as they become available. The main processing loop will iterate over the workers several times. The first time, any workers that have completed their task will mark them as completed. The next iteration through will assign the next available task to the workers, if any are available. Once all the tasks are assigned, or all the workers are processing something, we’ll increment a “timer” variable, and decrement each worker’s remaining time. Once all tasks are complete, our timer variable will have our answer to part 2.
|
|
The complete code for this puzzle is available, along with the other days, on my Gitlab repository https://gitlab.com/aarynsmith/adventofcode/blob/master/2018/Day_7/Day7.go
If you have any questions or comments, please feel free comment below.