-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_03.rs
95 lines (82 loc) · 2.39 KB
/
day_03.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
89
90
91
92
93
94
95
fn get_offset(is_uppercase: bool) -> u32 {
if is_uppercase {
64 - 26
} else {
96
}
}
pub fn part_1(input: &str) -> u32 {
input
.lines()
.map(|line| line.split_at(line.len() / 2))
.fold(0, |acc, (left, right)| {
let duplicate = left
.chars()
.find(|lc| right.chars().any(|rc| rc.eq(lc)))
.unwrap();
acc + (duplicate as u32) - get_offset(duplicate.is_uppercase())
})
}
pub fn part_2(input: &str) -> u32 {
let lines: Vec<&str> = input.lines().collect();
lines.chunks(3).fold(0, |acc, group| {
let badge = group[0]
.chars()
.find(|c| group[1].chars().any(|c2| c2.eq(c)) && group[2].chars().any(|c2| c2.eq(c)))
.unwrap();
acc + (badge as u32) - get_offset(badge.is_uppercase())
})
}
pub fn part_2_sorted(input: &str) -> u32 {
let lines: Vec<&str> = input.lines().collect();
lines.chunks(3).fold(0, |acc, group| {
let mut clone = group.to_vec();
clone.sort();
let badge = clone[0]
.chars()
.find(|c| group[1].chars().any(|c2| c2.eq(c)) && group[2].chars().any(|c2| c2.eq(c)))
.unwrap();
acc + (badge as u32) - get_offset(badge.is_uppercase())
})
}
#[cfg(test)]
mod tests {
use crate::get_input;
use super::*;
#[test]
fn test_part_1_dummy() {
let input = get_input("2022", "03", Some("dummy"));
let output = part_1(&input);
assert_eq!(output, 157);
}
#[test]
fn test_part_1() {
let input = get_input("2022", "03", None);
let output = part_1(&input);
assert_eq!(output, 8153);
}
#[test]
fn test_part_2_dummy() {
let input = get_input("2022", "03", Some("dummy"));
let output = part_2(&input);
assert_eq!(output, 70);
}
#[test]
fn test_part_2() {
let input = get_input("2022", "03", None);
let output = part_2(&input);
assert_eq!(output, 2342);
}
#[test]
fn test_part_2_dummy_sorted() {
let input = get_input("2022", "03", Some("dummy"));
let output = part_2_sorted(&input);
assert_eq!(output, 78);
}
#[test]
fn test_part_2_sorted() {
let input = get_input("2022", "03", None);
let output = part_2_sorted(&input);
assert_eq!(output, 2985);
}
}