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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
use std::collections::{HashMap, HashSet};
pub fn part1(input: &str) -> usize {
let mut tot: usize = 0;
let lines = input
.lines()
.map(|x| String::from(x))
.collect::<Vec<String>>();
let mut map = HashMap::<char, usize>::new();
for (i, ch) in ('a'..='z').enumerate() {
map.insert(ch, i + 1);
}
for (i, ch) in ('A'..='Z').enumerate() {
map.insert(ch, i + 27);
}
for line in lines {
let half = line.len() / 2;
let (l, r) = (&line[0..half], &line[half..]);
'o: for ch in l.chars() {
for ch2 in r.chars() {
if ch == ch2 {
tot += map[&ch];
break 'o;
}
}
}
}
tot
}
pub fn part2(input: &str) -> usize {
let mut tot: usize = 0;
let lines = input
.lines()
.map(|x| String::from(x))
.collect::<Vec<String>>();
let mut map = HashMap::<char, usize>::new();
for (i, ch) in ('a'..='z').enumerate() {
map.insert(ch, i + 1);
}
for (i, ch) in ('A'..='Z').enumerate() {
map.insert(ch, i + 27);
}
let n = lines.len() / 3;
let mut group_of_3 = Vec::<Vec<String>>::with_capacity(n);
for _ in 0..n {
group_of_3.push(vec![]);
}
let mut idx = 0;
for (i, line) in lines.iter().enumerate() {
if i % 3 == 0 && i != 0 {
idx += 1;
}
group_of_3[idx].push(line.to_string());
}
for g in group_of_3 {
let mut h1 = HashSet::new();
let mut h2 = HashSet::new();
for ch in g[0].chars() {
h1.insert(ch);
}
for ch in g[1].chars() {
h2.insert(ch);
}
for ch in g[2].chars() {
if h1.contains(&ch) && h2.contains(&ch) {
tot += map[&ch];
break;
}
}
}
tot
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_example() {
let data = include_str!("../example.txt");
let result = part1(data);
assert_eq!(result, 157);
}
#[test]
fn test_input() {
let data = include_str!("../input.txt");
let result = part1(data);
assert_eq!(result, 7428);
}
#[test]
fn test_example_2() {
let data = include_str!("../example.txt");
let result = part2(data);
assert_eq!(result, 70);
}
#[test]
fn test_input_2() {
let data = include_str!("../input.txt");
let result = part2(data);
assert_eq!(result, 2650);
}
}
|