-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday05.rs
More file actions
106 lines (91 loc) · 2.6 KB
/
day05.rs
File metadata and controls
106 lines (91 loc) · 2.6 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use std::cmp::Ordering;
use std::collections::HashSet;
fn parse_input(input: &str) -> (HashSet<(usize, usize)>, Vec<Vec<usize>>) {
let mut ordering: HashSet<(usize, usize)> = HashSet::new();
let mut books: Vec<Vec<usize>> = Vec::new();
let mut first_part = true;
for mut line in input.lines() {
line = line.trim();
if first_part {
if line.is_empty() {
first_part = false;
continue;
}
let (parent, child) = line
.split_once("|")
.map(|(left, right)| {
(
left.parse::<usize>().unwrap(),
right.parse::<usize>().unwrap(),
)
})
.unwrap();
ordering.insert((parent, child));
} else {
let book: Vec<usize> = line
.split(",")
.map(|x| x.parse::<usize>().unwrap())
.collect();
books.push(book);
}
}
(ordering, books)
}
fn get_center(book: &Vec<usize>) -> Option<usize> {
if book.len() % 2 == 0 {
return None;
}
let mid = book.len() / 2;
Some(book[mid])
}
fn task(input: &str, sorted_books: bool) -> String {
let (ordering, mut books) = parse_input(input);
let mut result = 0;
for book in books.iter_mut() {
let orig_book = book.clone();
(*book).sort_by(|a, b| {
if ordering.contains(&(*a, *b)) {
return Ordering::Less;
}
if ordering.contains(&(*b, *a)) {
return Ordering::Greater;
}
return Ordering::Equal;
});
if (*book == orig_book && sorted_books) || (!sorted_books && *book != orig_book) {
result += get_center(book).expect("No center found");
}
}
result.to_string()
}
pub fn task01(input: &str) -> String {
return task(input, true);
}
pub fn task02(input: &str) -> String {
return task(input, false);
}
#[cfg(test)]
mod tests {
use super::super::fs_utils::{read_example, read_input};
use super::*;
#[test]
fn test_task01() {
let input = read_example(5, 1);
assert_eq!(task01(&input), "143");
}
#[test]
fn run_task01() {
let input = read_input(5);
assert_eq!(task01(&input), "5955");
}
#[test]
fn test_task02() {
let input = read_example(5, 1);
assert_eq!(task02(&input), "123");
}
#[test]
fn run_task02() {
let input = read_input(5);
assert_eq!(task02(&input), "4030");
}
}