AoC 2022 D25: Full of Hot Air
| Problem statement | Source code | Tags: Mathematics
There are two solutions that probably work equally well: one is to convert the SNAFU number to decimal, do the math, and convert back to SNAFU. The other is to do the math directly in SNAFU. I went with the second approach because it looks more mathy.
A SNAFU number can be represented as:
Where and starts from the rightmost digit. I store it as a list of digits from the least significant one.
Now, to do addition for , we have the recurrence:
How the digit and carry are derived just requires casework. Our goal is to make the digit between -2 and 2, while can be at least -5 (if both digits are -2 and the carry is -1) and at most 5 (if both digits are 2 and the carry is 1).
- If , then we need to add 5 to it, which generates a carry of -1. , so , and .
- If , then we don't need to add anything, and the carry is 0. , so , and .
- If , then we need to subtract 5 from it, which generates a carry of 1. , so , and .
As for the implementation, I implemented it as a three-way addition of number 1, number 2, and the carry. It stops when both numbers are empty and the carry is 0.