Skip to content

Commit eabe207

Browse files
committed
Document Year 2022 Day 25
1 parent 9808f35 commit eabe207

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

src/year2022/day25.rs

+18-8
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
1-
pub fn parse(input: &str) -> Vec<&[u8]> {
2-
input.lines().map(str::as_bytes).collect()
1+
//! # Full of Hot Air
2+
//!
3+
//! The SNAFU numbers are balanced quinary, similar to
4+
//! [an actual base](https://en.wikipedia.org/wiki/Balanced_ternary)
5+
//! used by some experimental computers.
6+
pub fn parse(input: &str) -> Vec<&str> {
7+
input.lines().collect()
38
}
49

5-
pub fn part1(input: &[&[u8]]) -> String {
10+
pub fn part1(input: &[&str]) -> String {
611
to_snafu(input.iter().map(from_snafu).sum())
712
}
813

9-
pub fn part2(_input: &[&[u8]]) -> &'static str {
14+
pub fn part2(_input: &[&str]) -> &'static str {
1015
"n/a"
1116
}
1217

13-
fn from_snafu(snafu: &&[u8]) -> i64 {
14-
snafu.iter().fold(0, |acc, c| {
18+
/// Converting from SNAFU to decimal is straightforward.
19+
fn from_snafu(snafu: &&str) -> i64 {
20+
snafu.bytes().fold(0, |acc, c| {
1521
let digit = match c {
1622
b'=' => -2,
1723
b'-' => -1,
@@ -24,8 +30,10 @@ fn from_snafu(snafu: &&[u8]) -> i64 {
2430
})
2531
}
2632

27-
fn to_snafu(decimal: i64) -> String {
28-
let mut n = decimal;
33+
/// Convert to decimal by first finding the result modulus 5 for each digit.
34+
/// If the answer is 3 or 4 then we must add a carry to the next digit so account for the
35+
/// subtraction.
36+
fn to_snafu(mut n: i64) -> String {
2937
let mut digits = String::new();
3038

3139
while n > 0 {
@@ -38,6 +46,8 @@ fn to_snafu(decimal: i64) -> String {
3846
_ => unreachable!(),
3947
};
4048
digits.insert(0, next);
49+
// If the remainder of n is 3 or higher then this will add a carry digit to account
50+
// for the subtraction.
4151
n = (n + 2) / 5;
4252
}
4353

0 commit comments

Comments
 (0)