Skip to content

Commit

Permalink
Merge pull request #224 from paulcacheux/day9-2023
Browse files Browse the repository at this point in the history
Day9 2023
  • Loading branch information
paulcacheux authored Dec 9, 2023
2 parents 0e23cc7 + 7b76ba2 commit 3476e6b
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 0 deletions.
3 changes: 3 additions & 0 deletions inputs/2023/day9_test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
5 changes: 5 additions & 0 deletions results/2023.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,10 @@
"day": 8,
"part1": "13771",
"part2": "13129439557681"
},
{
"day": 9,
"part1": "1702218515",
"part2": "925"
}
]
70 changes: 70 additions & 0 deletions src/aoc2023/day9.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use crate::aoc2023::Aoc2023;
use crate::traits::days::Day9;
use crate::traits::ParseInput;
use crate::traits::Solution;

impl ParseInput<Day9> for Aoc2023 {
type Parsed = Vec<Vec<i32>>;

fn parse_input(input: &str) -> Self::Parsed {
input
.lines()
.map(|line| {
line.split_ascii_whitespace()
.map(|value| value.parse().unwrap())
.collect()
})
.collect()
}
}

impl Solution<Day9> for Aoc2023 {
type Part1Output = i32;
type Part2Output = i32;

fn part1(input: &Vec<Vec<i32>>) -> i32 {
solve(input, false)
}

fn part2(input: &Vec<Vec<i32>>) -> i32 {
solve(input, true)
}
}

fn solve(input: &Vec<Vec<i32>>, part2: bool) -> i32 {
let mut sum = 0;
for line in input {
let mut history = Vec::new();
let mut current = line.clone();

while !current.iter().all(|&v| v == 0) {
history.push(
*(if part2 {
current.first()
} else {
current.last()
})
.unwrap(),
);

let mut next_line: Vec<i32> = Vec::with_capacity(current.len() - 1);
for [a, b] in current.array_windows() {
let delta = b - a;
next_line.push(delta);
}
current = next_line;
}

sum += history.into_iter().rev().fold(
0,
|acc, value| {
if part2 {
value - acc
} else {
value + acc
}
},
);
}
sum
}
2 changes: 2 additions & 0 deletions src/aoc2023/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub mod day5;
pub mod day6;
pub mod day7;
pub mod day8;
pub mod day9;

pub fn run_solution_for_day(day: u32, input: &str, results: Option<Results>) -> Option<TimingData> {
let r = results
Expand All @@ -26,6 +27,7 @@ pub fn run_solution_for_day(day: u32, input: &str, results: Option<Results>) ->
6 => run::<Aoc2023, Day6>(input, r),
7 => run::<Aoc2023, Day7>(input, r),
8 => run::<Aoc2023, Day8>(input, r),
9 => run::<Aoc2023, Day9>(input, r),
_ => return None,
};
Some(elapsed)
Expand Down

0 comments on commit 3476e6b

Please sign in to comment.