-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.rs
113 lines (95 loc) · 2.7 KB
/
day7.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//! [Day 7: Internet Protocol Version 7](https://adventofcode.com/2016/day/7)
use rustc_hash::FxHashSet;
pub fn main() {
let args = aoc::parse_args();
args.run(solve);
}
/// # Panics
#[must_use]
pub fn solve(data: &str) -> (usize, usize) {
(part1(data), part2(data))
}
/// ``part1`` counts the IPs that support TLS
fn part1(data: &str) -> usize {
data.lines().filter(|s| support_tls(s)).count()
}
/// ``part2`` counts the IPs that support SSL
fn part2(data: &str) -> usize {
data.lines().filter(|s| support_ssl(s)).count()
}
/// ``support_tls`` looks for an ABBA pattern outside brackets, and not within
fn support_tls(address: &str) -> bool {
let mut has_abba = false;
let mut hypernet = false;
for i in 0..=address.len() - 4 {
let a = address.chars().nth(i).unwrap();
if a == '[' {
hypernet = true;
continue;
}
if a == ']' {
hypernet = false;
continue;
}
let b = address.chars().nth(i + 1).unwrap();
let c = address.chars().nth(i + 2).unwrap();
let d = address.chars().nth(i + 3).unwrap();
if a == d && b == c && a != b {
if hypernet {
return false;
}
has_abba = true;
}
}
has_abba
}
/// ``support_ssl`` tests for ABA patterns outside brackets and BAB within brackets
fn support_ssl(address: &str) -> bool {
let mut hypernet = false;
let mut supernet_aba = FxHashSet::default();
let mut hypernet_bab = FxHashSet::default();
for i in 0..=address.len() - 3 {
let a = address.chars().nth(i).unwrap();
if a == '[' {
hypernet = true;
continue;
}
if a == ']' {
hypernet = false;
continue;
}
let b = address.chars().nth(i + 1).unwrap();
let c = address.chars().nth(i + 2).unwrap();
if a == c && a != b {
if hypernet {
hypernet_bab.insert((b, a, b));
} else {
supernet_aba.insert((a, b, a));
}
}
}
for aba in supernet_aba {
if hypernet_bab.contains(&aba) {
return true;
}
}
false
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_tls() {
assert!(support_tls("abba[mnop]qrst"));
assert!(!support_tls("abcd[bddb]xyyx"));
assert!(!support_tls("aaaa[qwer]tyui"));
assert!(support_tls("ioxxoj[asdfgh]zxcvbn"));
}
#[test]
fn test_ssl() {
assert!(support_ssl("aba[bab]xyz"));
assert!(!support_ssl("xyx[xyx]xyx"));
assert!(support_ssl("aaa[kek]eke"));
assert!(support_ssl("zazbz[bzb]cdb"));
}
}