Skip to content

Commit b85f7f1

Browse files
committed
Add day5 part2
1 parent 3762255 commit b85f7f1

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

src/day5.rs

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use aoc_runner_derive::{aoc, aoc_generator};
2-
use std::collections::HashMap;
2+
use std::{cmp::Ordering, collections::HashMap, vec};
33

44
#[derive(Debug)]
55
pub struct Rules {
@@ -19,7 +19,6 @@ pub fn input_generator(input: &str) -> Rules {
1919
.entry(sides.1.parse().unwrap())
2020
.or_insert_with(Vec::new)
2121
.push(sides.0.parse().unwrap());
22-
// ordering.push(l.split("|").map(|s| s.parse().unwrap()).collect());
2322
}
2423
if l.contains(",") {
2524
updates.push(l.split(",").map(|s| s.parse().unwrap()).collect());
@@ -46,6 +45,39 @@ pub fn part1(input: &Rules) -> usize {
4645
total
4746
}
4847

48+
#[aoc(day5, part2)]
49+
pub fn part2(input: &Rules) -> usize {
50+
let mut invalids = vec![];
51+
'outer: for update in &input.updates {
52+
for n in 0..update.len() {
53+
if let Some(must_be_before) = input.ordering.get(&update[n]) {
54+
for m in update.iter().skip(n) {
55+
if must_be_before.contains(m) {
56+
invalids.push(update);
57+
continue 'outer;
58+
}
59+
}
60+
}
61+
}
62+
}
63+
64+
let mut total = 0;
65+
for invalid in invalids {
66+
let mut inv = invalid.clone();
67+
inv.sort_by(|a, b| {
68+
dbg!(a, b);
69+
if let Some(must_be_before) = input.ordering.get(b) {
70+
if must_be_before.contains(a) {
71+
return Ordering::Less;
72+
}
73+
}
74+
Ordering::Equal
75+
});
76+
total += inv[inv.len() / 2]
77+
}
78+
total
79+
}
80+
4981
#[cfg(test)]
5082
mod tests {
5183
use super::*;
@@ -84,8 +116,8 @@ mod tests {
84116
assert_eq!(143, part1(&input_generator(INPUT)))
85117
}
86118

87-
// #[test]
88-
// fn test_part2() {
89-
// assert_eq!(9, part2(&input_generator(INPUT)))
90-
// }
119+
#[test]
120+
fn test_part2() {
121+
assert_eq!(123, part2(&input_generator(INPUT)))
122+
}
91123
}

0 commit comments

Comments
 (0)