|
| 1 | +//! # LAN Party |
| 2 | +use crate::util::hash::*; |
| 3 | + |
| 4 | +type Input = (FastMap<usize, Vec<usize>>, Vec<[bool; 676]>); |
| 5 | + |
| 6 | +pub fn parse(input: &str) -> Input { |
| 7 | + let mut nodes = FastMap::with_capacity(1_000); |
| 8 | + let mut edges = vec![[false; 676]; 676]; |
| 9 | + |
| 10 | + let to_index = |b: &[u8]| 26 * to_usize(b[0]) + to_usize(b[1]); |
| 11 | + let empty = || Vec::with_capacity(16); |
| 12 | + |
| 13 | + for edge in input.as_bytes().chunks(6) { |
| 14 | + let from = to_index(&edge[..2]); |
| 15 | + let to = to_index(&edge[3..]); |
| 16 | + |
| 17 | + nodes.entry(from).or_insert_with(empty).push(to); |
| 18 | + nodes.entry(to).or_insert_with(empty).push(from); |
| 19 | + |
| 20 | + edges[from][to] = true; |
| 21 | + edges[to][from] = true; |
| 22 | + } |
| 23 | + |
| 24 | + (nodes, edges) |
| 25 | +} |
| 26 | + |
| 27 | +pub fn part1(input: &Input) -> usize { |
| 28 | + let (nodes, edges) = input; |
| 29 | + let mut seen = [false; 676]; |
| 30 | + let mut triangles = 0; |
| 31 | + |
| 32 | + for n1 in 494..520 { |
| 33 | + if let Some(neighbours) = nodes.get(&n1) { |
| 34 | + seen[n1] = true; |
| 35 | + |
| 36 | + for (i, &n2) in neighbours.iter().enumerate() { |
| 37 | + for &n3 in neighbours.iter().skip(i) { |
| 38 | + if !seen[n2] && !seen[n3] && edges[n2][n3] { |
| 39 | + triangles += 1; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + triangles |
| 47 | +} |
| 48 | + |
| 49 | +pub fn part2(input: &Input) -> String { |
| 50 | + let (nodes, edges) = input; |
| 51 | + let mut seen = [false; 676]; |
| 52 | + let mut clique = Vec::new(); |
| 53 | + let mut largest = Vec::new(); |
| 54 | + |
| 55 | + for (&n1, neighbours) in nodes { |
| 56 | + if !seen[n1] { |
| 57 | + clique.clear(); |
| 58 | + clique.push(n1); |
| 59 | + |
| 60 | + for &n2 in neighbours { |
| 61 | + if clique.iter().all(|&c| edges[n2][c]) { |
| 62 | + seen[n2] = true; |
| 63 | + clique.push(n2); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + if clique.len() > largest.len() { |
| 68 | + largest.clone_from(&clique); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + let mut result = String::new(); |
| 74 | + largest.sort_unstable(); |
| 75 | + |
| 76 | + for n in largest { |
| 77 | + result.push(to_char(n / 26)); |
| 78 | + result.push(to_char(n % 26)); |
| 79 | + result.push(','); |
| 80 | + } |
| 81 | + |
| 82 | + result.pop(); |
| 83 | + result |
| 84 | +} |
| 85 | + |
| 86 | +fn to_usize(b: u8) -> usize { |
| 87 | + (b - b'a') as usize |
| 88 | +} |
| 89 | + |
| 90 | +fn to_char(u: usize) -> char { |
| 91 | + ((u as u8) + b'a') as char |
| 92 | +} |
0 commit comments