diff options
| author | Reiner Herrmann <reiner@reiner-h.de> | 2023-12-09 22:28:14 +0100 |
|---|---|---|
| committer | Reiner Herrmann <reiner@reiner-h.de> | 2023-12-09 22:28:14 +0100 |
| commit | c85f47a55d1c116a815f403f935b85a296bc0354 (patch) | |
| tree | b7c90912f491ff5f9a5f05ca739654ff495c3c6a /src/bin/day9.rs | |
| parent | 08d47acd87b452e12bd014471dfc472bfad7788e (diff) | |
day9 solution 1
Diffstat (limited to 'src/bin/day9.rs')
| -rw-r--r-- | src/bin/day9.rs | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/bin/day9.rs b/src/bin/day9.rs new file mode 100644 index 0000000..ec008fb --- /dev/null +++ b/src/bin/day9.rs @@ -0,0 +1,43 @@ +static DAY: u8 = 9; + +fn main() { + let input = advent::read_lines(DAY); + println!("{DAY}a: {}", sum_extrapolations(&input)); + println!("{DAY}b: {}", 0); +} + +fn extrapolate(input: &[i32]) -> i32 { + if input.iter().all(|&n| n == 0) { + /* all zeroes */ + return 0; + } + + let diffs = input.iter() + .as_slice() + .windows(2) + .map(|x| x[1] - x[0]) + .collect::<Vec<_>>(); + input.last().unwrap() + extrapolate(&diffs) +} + +fn sum_extrapolations(input: &[String]) -> i32 { + input.iter() + .map(|x| x.split(' ').map(|n| n.parse().unwrap()).collect::<Vec<_>>()) + .map(|numbers| extrapolate(&numbers)) + .sum() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test() { + let input = [ + "0 3 6 9 12 15", + "1 3 6 10 15 21", + "10 13 16 21 30 45", + ].iter().map(|&x| String::from(x)).collect::<Vec<_>>(); + assert_eq!(sum_extrapolations(&input), 114); + } +} |
