diff --git a/2016/rust/src/day_07.rs b/2016/rust/src/day_07.rs index 3a759cb..8edb446 100644 --- a/2016/rust/src/day_07.rs +++ b/2016/rust/src/day_07.rs @@ -3,7 +3,7 @@ use errors::*; pub fn solve(input: &str) -> Result { Ok(input.lines() .map(|x| IP7::new(x)) - .filter(IP7::supports_tls) + .filter(IP7::supports_ssl) .count() .to_string()) } @@ -40,15 +40,36 @@ impl IP7 { } } - fn supports_tls(&self) -> bool { + pub fn supports_tls(&self) -> bool { self.supernets.iter().any(|x| Self::abba(x)) && self.hypernets.iter().all(|x| !Self::abba(x)) } + fn supports_ssl(&self) -> bool { + let abas: Vec = + self.supernets.iter().flat_map(|x| { + Self::abas(x).iter().map(|aba| { + let mut c = aba.chars(); + let a = c.next().unwrap(); + let b = c.next().unwrap(); + format!("{}{}{}", b, a, b) + }).collect::>() + }).collect(); + self.hypernets.iter().any(|x| abas.iter().any(|y| x.contains(y))) + } + fn abba(s: &str) -> bool { let v: Vec<_> = s.chars().collect(); v.windows(4).any(|w| (w[0] != w[1]) && (w[0] == w[3]) && (w[1] == w[2])) } + + fn abas(s: &str) -> Vec { + let v: Vec<_> = s.chars().collect(); + v.windows(3) + .filter(|w| (w[0] != w[1]) && (w[0] == w[2])) + .map(|w| w.iter().map(|&x| x).collect()) + .collect() + } } #[cfg(test)] @@ -75,4 +96,18 @@ mod tests { assert_eq!(IP7::new("aaaa[qwer]tyui").supports_tls(), false); assert_eq!(IP7::new("ioxxoj[asdfgh]zxcvbn").supports_tls(), true); } + + #[test] + fn test_abas() { + assert_eq!(IP7::abas("zazbz"), + vec!["zaz".to_string(), "zbz".to_string()]); + } + + #[test] + fn test_supports_ssl() { + assert!(IP7::new("aba[bab]xyz").supports_ssl()); + assert!(!IP7::new("xyx[xyx]xyx").supports_ssl()); + assert!(IP7::new("aaa[kek]eke").supports_ssl()); + assert!(IP7::new("zazbz[bzb]cdb").supports_ssl()); + } }