Skip to content

Commit bd3594c

Browse files
committed
day 1
1 parent a681b29 commit bd3594c

File tree

4 files changed

+80
-0
lines changed

4 files changed

+80
-0
lines changed

Cargo.lock

Lines changed: 16 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ test_lib = []
2424
# Template dependencies
2525
chrono = { version = "0.4.38", optional = true }
2626
dhat = { version = "0.3.3", optional = true }
27+
itertools = "0.13.0"
2728
pico-args = "0.5.0"
2829
tinyjson = "2.5.1"
2930

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

src/bin/01.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
advent_of_code::solution!(1);
2+
use itertools::Itertools;
3+
4+
fn parse_input(input: &str) -> (Vec<u32>, Vec<u32>) {
5+
let mut l1 = Vec::with_capacity(1000);
6+
let mut l2 = Vec::with_capacity(1000);
7+
for line in input.lines() {
8+
let mut parts = line.split_whitespace();
9+
let n1 = parts.next().unwrap().parse::<u32>().unwrap();
10+
let n2 = parts.next().unwrap().parse::<u32>().unwrap();
11+
l1.push(n1);
12+
l2.push(n2);
13+
}
14+
(l1, l2)
15+
}
16+
17+
pub fn part_one(input: &str) -> Option<u32> {
18+
let (mut l1, mut l2) = parse_input(input);
19+
20+
l1.sort();
21+
l2.sort();
22+
23+
let mut total = 0;
24+
for (n1, n2) in l1.iter().zip(l2.iter()) {
25+
total += n1.abs_diff(*n2);
26+
}
27+
Some(total)
28+
}
29+
30+
pub fn part_two(input: &str) -> Option<u32> {
31+
let (l1, l2) = parse_input(input);
32+
let freq = l2.iter().counts();
33+
let mut total = 0;
34+
for n1 in l1 {
35+
if let Some(&n2) = freq.get(&n1) {
36+
total += n1 * n2 as u32;
37+
}
38+
}
39+
Some(total)
40+
}
41+
42+
#[cfg(test)]
43+
mod tests {
44+
use super::*;
45+
46+
#[test]
47+
fn test_part_one() {
48+
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
49+
assert_eq!(result, Some(11));
50+
}
51+
52+
#[test]
53+
fn test_part_two() {
54+
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
55+
assert_eq!(result, Some(31));
56+
}
57+
}

0 commit comments

Comments
 (0)