Skip to content

Commit

Permalink
feat: day 1
Browse files Browse the repository at this point in the history
  • Loading branch information
JosefKuchar committed Dec 1, 2024
1 parent a0ae067 commit 5133f1a
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ test_lib = []
# Template dependencies
chrono = { version = "0.4.38", optional = true }
dhat = { version = "0.3.3", optional = true }
itertools = "0.13.0"
pico-args = "0.5.0"
tinyjson = "2.5.1"

Expand Down
6 changes: 6 additions & 0 deletions data/examples/01.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
3 4
4 3
2 5
1 3
3 9
3 3
51 changes: 51 additions & 0 deletions src/bin/01.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use itertools::Itertools;

advent_of_code::solution!(1);

fn get_lists(input: &str) -> (Vec<u32>, Vec<u32>) {
let numbers: Vec<u32> = input
.lines()
.flat_map(|line| line.split_whitespace().map(|x| x.parse::<u32>().unwrap()))
.collect();
let left = numbers.iter().step_by(2).map(|x| *x).collect();
let right = numbers.iter().skip(1).map(|x| *x).step_by(2).collect();

(left, right)
}

pub fn part_one(input: &str) -> Option<u32> {
let (left, right) = get_lists(input);
Some(
left.iter()
.sorted()
.zip(right.iter().sorted())
.map(|(l, r)| l.abs_diff(*r))
.sum(),
)
}

pub fn part_two(input: &str) -> Option<u32> {
let (left, right) = get_lists(input);
Some(
left.iter()
.map(|l| l * right.iter().filter(|r| *r == l).count() as u32)
.sum(),
)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(11));
}

#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(31));
}
}

0 comments on commit 5133f1a

Please sign in to comment.