Skip to content

Commit 123726a

Browse files
Solve Day 5 Part 1
1 parent 6b17408 commit 123726a

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

data/examples/05.txt

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
47|53
2+
97|13
3+
97|61
4+
97|47
5+
75|29
6+
61|13
7+
75|53
8+
29|13
9+
97|29
10+
53|29
11+
61|53
12+
97|53
13+
61|29
14+
47|13
15+
75|47
16+
97|75
17+
47|61
18+
75|61
19+
47|29
20+
75|13
21+
53|13
22+
23+
75,47,61,53,29
24+
97,61,53,29,13
25+
75,29,13
26+
75,97,47,61,53
27+
61,13,29
28+
97,13,75,29,47

src/bin/05.rs

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
advent_of_code::solution!(5);
2+
3+
use itertools::Itertools;
4+
5+
pub fn part_one(input: &str) -> Option<u32> {
6+
let parts = input.splitn(2, "\n\n").collect::<Vec<&str>>();
7+
let rules_section = parts[0];
8+
let updates_section = parts[1];
9+
let rules: Vec<(i32, i32)> = rules_section
10+
.lines()
11+
.map(|line| {
12+
let l: Vec<&str> = line.splitn(2, '|').collect();
13+
(l[0].parse().unwrap(), l[1].parse().unwrap())
14+
})
15+
.collect();
16+
17+
let updates: Vec<Vec<i32>> = updates_section
18+
.lines()
19+
.map(|line| {
20+
line.split(',')
21+
.filter_map(|x| x.parse::<i32>().ok())
22+
.collect::<Vec<i32>>()
23+
})
24+
.collect();
25+
26+
updates
27+
.iter()
28+
.filter(|update| {
29+
// combinations will keep pairs in their relative ordering from the original vector
30+
update.iter().combinations(2).all(|pair| {
31+
let first = pair[0];
32+
let second = pair[1];
33+
let invalid = rules.iter().any(|(x, y)| first == y && second == x);
34+
35+
!invalid
36+
})
37+
})
38+
.map(|update| update[update.len() / 2])
39+
.sum::<i32>()
40+
.try_into()
41+
.ok()
42+
}
43+
44+
pub fn part_two(input: &str) -> Option<u32> {
45+
None
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(143));
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, None);
62+
}
63+
}

0 commit comments

Comments
 (0)