diff --git a/samples/day25.txt b/samples/day25.txt new file mode 100644 index 0000000..237ef0c --- /dev/null +++ b/samples/day25.txt @@ -0,0 +1,13 @@ +1=-0-2 +12111 +2=0= +21 +2=01 +111 +20012 +112 +1=-1= +1-12 +12 +1= +122 \ No newline at end of file diff --git a/src/bin/day25.rs b/src/bin/day25.rs new file mode 100644 index 0000000..2a369ae --- /dev/null +++ b/src/bin/day25.rs @@ -0,0 +1,122 @@ +use std::{char::from_digit, collections::HashMap}; + +use aoc_2022::*; + +type Input = Vec; +type Output = String; + +fn from_snafu(s: &str) -> isize { + (0..) + .zip(s.chars().rev()) + .map(|(e, d)| { + 5_isize.pow(e) + * match d { + '-' => -1, + '=' => -2, + _ => d.to_digit(10).unwrap().try_into().unwrap(), + } + }) + .sum() +} + +fn to_snafu(mut n: isize) -> String { + let mut digits: Vec = Vec::new(); + + while n > 0 { + let mut d = n % 5; + if d > 2 { + n += 5 - d; + d -= 5; + } + + digits.push(match d { + -1 => '-', + -2 => '=', + _ => from_digit(d as u32, 10).unwrap(), + }); + + n /= 5; + } + + digits.reverse(); + + digits.iter().join("") +} + +struct Day25; +impl Solution for Day25 { + fn parse_input>(pathname: P) -> Input { + file_to_lines(pathname) + } + + fn part_1(input: &Input) -> Output { + to_snafu(input.iter().map(|s| from_snafu(s)).sum()) + } + + fn part_2(_input: &Input) -> Output { + "Merry Chrysler!!!".to_string() + } +} + +fn main() -> Result<()> { + // Day25::run("sample") + Day25::main() +} + +test_sample!( + day_25, + Day25, + "2=-1=0".to_string(), + "Merry Chrysler!!!".to_string() +); + +lazy_static! { + static ref EXAMPLES: HashMap = HashMap::from([ + (1, "1"), + (2, "2"), + (3, "1="), + (4, "1-"), + (5, "10"), + (6, "11"), + (7, "12"), + (8, "2="), + (9, "2-"), + (10, "20"), + (15, "1=0"), + (20, "1-0"), + (2022, "1=11-2"), + (12345, "1-0---0"), + (314159265, "1121-1110-1=0"), + (1747, "1=-0-2"), + (906, "12111"), + (198, "2=0="), + (11, "21"), + (201, "2=01"), + (31, "111"), + (1257, "20012"), + (32, "112"), + (353, "1=-1="), + (107, "1-12"), + (37, "122"), + (4890, "2=-1=0"), + ]); +} + +#[cfg(test)] +mod day_25_snafu { + use super::*; + + #[test] + fn test_from() { + for (n, s) in EXAMPLES.iter() { + assert_eq!(from_snafu(s), *n); + } + } + + #[test] + fn test_to() { + for (n, s) in EXAMPLES.iter() { + assert_eq!(to_snafu(*n), s.to_string()); + } + } +}