Skip to content

Commit 10003a7

Browse files
committed
AOC 2024 Day 01
1 parent 5a07319 commit 10003a7

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

aoc/2024/rust/data/examples/01.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
3 4
2+
4 3
3+
2 5
4+
1 3
5+
3 9
6+
3 3

aoc/2024/rust/src/bin/01.rs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
use std::{collections::HashMap, i32, u32};
2+
3+
advent_of_code::solution!(1);
4+
5+
fn parse(input: &str) -> (Vec<i32>, Vec<i32>) {
6+
input
7+
.lines()
8+
.map(|line| {
9+
let mut nums = line
10+
.split_whitespace()
11+
.map(|s| s.parse::<i32>().expect("A valid parse"));
12+
let left = nums.next().expect("A value on the left column");
13+
let right = nums.next().expect("A value on the right column");
14+
(left, right)
15+
})
16+
.collect::<Vec<_>>() // Propagate the error if any
17+
.into_iter()
18+
.unzip()
19+
}
20+
21+
pub fn part_one(input: &str) -> Option<u32> {
22+
let (mut col1, mut col2) = parse(&input);
23+
col1.sort_unstable();
24+
col2.sort_unstable();
25+
Some(
26+
col1.into_iter()
27+
.zip(col2.into_iter())
28+
.map(|(a, b)| (a - b).abs() as u32)
29+
.sum::<u32>(),
30+
)
31+
}
32+
33+
pub fn part_two(input: &str) -> Option<u32> {
34+
let (col1, col2) = parse(&input);
35+
let mut counts = HashMap::new();
36+
for num in col2 {
37+
counts.entry(num).and_modify(|c| *c += 1).or_insert(1);
38+
}
39+
Some(col1.into_iter().fold(0, |acc, x| {
40+
if let Some(&right_count) = counts.get(&x) {
41+
acc + (x * right_count) as u32
42+
} else {
43+
acc
44+
}
45+
}))
46+
}
47+
48+
#[cfg(test)]
49+
mod tests {
50+
use super::*;
51+
52+
#[test]
53+
fn test_part_one() {
54+
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
55+
assert_eq!(result, Some(11));
56+
}
57+
58+
#[test]
59+
fn test_part_two() {
60+
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
61+
assert_eq!(result, Some(31));
62+
}
63+
}

0 commit comments

Comments
 (0)