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
//! # Internet Protocol Version 7
//!
//! It's faster to treat the entire input as one big stream, using line breaks to increment
//! the count if an address is valid.
//!
//! For part two there are at most 26 * 26 = 676 possible ABA or BAB sequences so we can use
//! a fixed size array to keep track of which ones we've seen for the current address so far.
pub fn parse(input: &str) -> &[u8] {
input.as_bytes()
}
pub fn part1(input: &[u8]) -> usize {
let mut count = 0;
let mut inside = false;
let mut positive = false;
let mut negative = false;
for w in input.windows(4) {
if w[0].is_ascii_lowercase() {
if w[0] == w[3] && w[1] == w[2] && w[0] != w[1] {
if inside {
negative = true;
} else {
positive = true;
}
}
} else if w[0] == b'[' {
inside = true;
} else if w[0] == b']' {
inside = false;
} else {
// Next line
if positive && !negative {
count += 1;
}
positive = false;
negative = false;
}
}
if positive && !negative {
count + 1
} else {
count
}
}
pub fn part2(input: &[u8]) -> usize {
let mut count = 0;
let mut version = 0;
let mut inside = false;
let mut positive = false;
let mut aba = [usize::MAX; 676];
let mut bab = [usize::MAX; 676];
for w in input.windows(3) {
if w[1].is_ascii_lowercase() {
if w[0] == w[2] && w[0] != w[1] {
let first = (w[0] - b'a') as usize;
let second = (w[1] - b'a') as usize;
if inside {
// Reverse the order of letters
let index = 26 * second + first;
bab[index] = version;
positive |= aba[index] == version;
} else {
let index = 26 * first + second;
aba[index] = version;
positive |= bab[index] == version;
}
}
} else if w[1] == b'[' {
inside = true;
} else if w[1] == b']' {
inside = false;
} else {
// Next line
if positive {
count += 1;
}
version += 1;
positive = false;
}
}
if positive {
count + 1
} else {
count
}
}