generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05.rs
88 lines (78 loc) · 2.49 KB
/
05.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use itertools::Itertools;
advent_of_code::solution!(5);
fn check_order(ordering: &[(u32, u32)], update: &[u32]) -> bool {
ordering.iter().all(|order| {
let first = update.iter().find_position(|x| x == &&order.0);
let second = update.iter().find_position(|x| x == &&order.1);
match (first, second) {
(Some((first, _)), Some((second, _))) => first < second,
_ => true,
}
})
}
fn parse_input(input: &str) -> (Vec<(u32, u32)>, Vec<Vec<u32>>) {
let parts = input.split("\n\n").collect::<Vec<&str>>();
let ordering = parts[0]
.lines()
.map(|line| {
let mut parts = line.split('|').map(|x| x.parse::<u32>().unwrap());
(parts.next().unwrap(), parts.next().unwrap())
})
.collect();
let updates = parts[1]
.lines()
.map(|line| {
line.split(',')
.map(|x| x.parse::<u32>().unwrap())
.collect::<Vec<u32>>()
})
.collect::<Vec<Vec<u32>>>();
(ordering, updates)
}
pub fn part_one(input: &str) -> Option<u32> {
let (ordering, updates) = parse_input(input);
Some(
updates
.iter()
.filter(|update| check_order(&ordering, update))
.map(|update| update[update.len() / 2])
.sum::<u32>(),
)
}
pub fn part_two(input: &str) -> Option<u32> {
let (ordering, updates) = parse_input(input);
Some(
updates
.iter()
.filter(|update| !check_order(&ordering, update))
.map(|update| {
let mut new_update = Vec::new();
for num in update {
for index in 0..update.len() {
let mut candidate = new_update.clone();
candidate.insert(index, *num);
if check_order(&ordering, &candidate) {
new_update = candidate;
break;
}
}
}
new_update[new_update.len() / 2]
})
.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(143));
}
#[test]
fn test_part_two() {
let result: Option<u32> = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(123));
}
}