Day 9 - Mirage Maintenance
link to Challenge
link to Github Repo
Table of Contents:
Breakdown
Parsing input
Extrapolating
Summing next in line
Conclusion
Breakdown
Parsing the Input
The ParseLine
method serves as a helper function to extract a list of numbers from each input line. It splits the line using the \n
character, removes any empty or whitespace-only entries, and converts the remaining characters to numbers using long.Parse
.
Extrapolating the Sequence
(don't worry I had to look up the Extrapolate definition too, and in the end, it just became a function name, rather than a "thing").
The Extrapolate method plays a crucial role. It takes a list of numbers as input and recursively extends the sequence to identify the differences.
The method first checks if the sequence consists entirely of zeros. If so, it simply inserts zeros at the beginning and end of the sequence to represent the extrapolated values.
For non-constant sequences, the method calculates the differences between consecutive pairs of elements using Zip
method read more here and creates a new sequence representing the differences between elements.
It then recursively calls the Extrapolate method with the nextSequence as the argument, effectively breaking down the original sequence into smaller subsequences, each handled by a separate recursive call.
Once the sequence is extrapolated, the method extracts the first and last differences from the extrapolated sequence. These represent the extrapolated values for the first and last elements of the original sequence.
The method updates the original sequence by adding the first and last differences to its start and end, respectively. This effectively extrapolates the original sequence to a larger range.
Phew, I hope you followed all that, it can be difficult explaining recursion within text format.
Summing the Next Numbers in each Sequence
After gathering all the next sequence numbers, Part 1 then selects the last element from each extrapolated sequence and calculates the sum of these elements.
After gathering all the next sequence numbers, Part 2 then selects the first element from each extrapolated sequence instead of the last.
Conclusion
The provided code effectively tackles the Day 9 challenge, utilizing recursion, to process the input data and identify the next numbers in a sequence. The code demonstrates the versatility of the C# language in solving complex problems using newer methods, and syntactical updates within .Net.
I know that recursion can be quite hard to follow, due to its complexity and almost Inception-like calling stack.
It took me a day or two to quite figure it all out and re-factor. I also learnt a method the Zip
method, which made things a lot easier than for-each loops.
Remember you can reach out on Twitter or drop me a follow and learn more about C# and other Tech topics I discuss.
Top comments (0)