generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05.rs
85 lines (76 loc) · 2.17 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
advent_of_code::solution!(5);
fn parse_input(input: &str) -> (Vec<Vec<u32>>, Vec<Vec<u32>>) {
let mut rules = Vec::new();
let mut updates = Vec::new();
for line in input.lines() {
if line.is_empty() {
continue;
}
if line.contains("|") {
rules.push(line.split("|").map(|s| s.parse().unwrap()).collect());
} else {
updates.push(line.split(",").map(|s| s.parse().unwrap()).collect());
}
}
(rules, updates)
}
pub fn part_one(input: &str) -> Option<u32> {
let (rules, updates) = parse_input(input);
Some(
updates
.iter()
.filter(|update| {
update.iter().zip(update.iter().skip(1)).all(|(&a, &b)| {
!rules.iter().any(|rule| rule[0] == b && rule[1] == a)
})
})
.map(|update| update[update.len() / 2])
.sum(),
)
}
fn correct(update: &mut Vec<u32>, rules: &Vec<Vec<u32>>) -> bool {
for i in 0..update.len() - 1 {
if rules
.iter()
.any(|rule| rule[1] == update[i] && rule[0] == update[i + 1])
{
update.swap(i, i + 1);
return true;
}
}
false
}
pub fn part_two(input: &str) -> Option<u32> {
let (rules, updates) = parse_input(input);
Some(
updates
.into_iter()
.filter(|update| {
update.iter().zip(update.iter().skip(1)).any(|(&a, &b)| {
rules.iter().any(|rule| rule[0] == b && rule[1] == a)
})
})
.map(|mut update| {
while correct(&mut update, &rules) {}
update
})
.map(|update| update[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 =
part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(123));
}
}