use std::{borrow::BorrowMut, collections::VecDeque, fmt::Display, fs::File, io::Write, mem::swap}; use aoc_runner_derive::aoc; use itertools::Itertools; use regex::Regex; use rustc_hash::{FxHashMap, FxHashSet}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum Op { And, Or, Xor, Constant, } impl From<&str> for Op { fn from(value: &str) -> Self { match value { "AND" => Self::And, "OR" => Self::Or, "XOR" => Self::Xor, s => panic!("invalid operation {}", s), } } } impl Display for Op { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Self::And => "AND", Self::Or => "OR", Self::Xor => "XOR", Self::Constant => "", }) } } #[derive(Clone, Debug)] struct Gate { op: Op, value: Option, arguments: [String; 2], } impl Display for Gate { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} {} {}", self.arguments[0], self.op, self.arguments[1]) } } impl Gate { fn eval(&self, machine: &GateMachine) -> bool { match self.op { Op::And => machine.val_of(&self.arguments[0]) && machine.val_of(&self.arguments[1]), Op::Or => machine.val_of(&self.arguments[0]) || machine.val_of(&self.arguments[1]), Op::Xor => machine.val_of(&self.arguments[0]) ^ machine.val_of(&self.arguments[1]), Op::Constant => self.value.unwrap(), } } } #[derive(Clone, Debug)] struct GateMachine { gates: FxHashMap, out_bits: usize, } impl GateMachine { fn val_of(&self, gate: &str) -> bool { if let Some(val) = self.gates[gate].value { val } else { self.gates[gate].eval(self) } } fn register(&self, reg: char) -> u64 { let reg_gates = self .gates .keys() .filter(|k| k.starts_with(reg)) .map(|s| (s, s.split_at(1).1.parse::().unwrap())); let val = reg_gates .map(|(name, bit)| if self.val_of(name) { 1 << bit } else { 0 }) .fold(0, |accum, val| accum | val); val } fn expected_result(&self) -> u64 { self.register('x') + self.register('y') & (1 << self.out_bits) - 1 } fn actual_result(&self) -> u64 { self.register('z') } fn swap(&mut self, a: &str, b: &str) { // for gate in self.gates.values_mut() { // for arg in gate.arguments.iter_mut() { // if arg == a { // *arg = b.to_string(); // } else if arg == b { // *arg = a.to_string() // } // } // } let a_tmp = self.gates[a].clone(); self.gates.insert(a.to_string(), self.gates[b].clone()); self.gates.insert(b.to_string(), a_tmp); } // return the gates that this gate depends on fn dependencies(&self, gate: &str) -> Vec<&str> { if let Some((key, arg)) = self.gates.get_key_value(gate) { let mut deps = vec![key.as_str()]; for dep in &arg.arguments { if dep != "" && self.gates[dep].op != Op::Constant { deps.push(dep.as_str()); deps.extend(self.dependencies(&dep).iter().copied()) } } deps } else if gate != "" { panic!("tried to look up invalid gate `{}`", gate); } else { Vec::new() } } // return the bits that this gate affects // fn dependents(&self, gate: &str) -> Vec<&str> {} fn reset(&mut self) { for gate in self.gates.values_mut().filter(|g| g.op != Op::Constant) { gate.value = None } } } fn parse(input: &str) -> GateMachine { let mut gates = FxHashMap::default(); for line in input.lines() { let const_re = Regex::new(r"^([xyz][0-9]{2}): ([01])$").unwrap(); let gate_re = Regex::new(r"^([a-z0-9]{3}) (AND|XOR|OR) ([a-z0-9]{3}) -> ([a-z0-9]{3})$").unwrap(); if let Some(caps) = const_re.captures(line) { gates.insert( caps[1].to_string(), Gate { op: Op::Constant, value: if &caps[2] == "1" { Some(true) } else { Some(false) }, arguments: [String::new(), String::new()], }, ); } else if let Some(caps) = gate_re.captures(line) { gates.insert( caps[4].to_string(), Gate { op: Op::from(&caps[2]), value: None, arguments: [caps[1].to_string(), caps[3].to_string()], }, ); } } let out_bits = gates .iter() .filter(|(k, _)| k.starts_with('z')) .map(|(k, _)| k.split_at(1).1.parse::().unwrap()) .max() .unwrap() as usize + 1; GateMachine { gates, out_bits } } impl Display for GateMachine { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for (name, gate) in self.gates.iter().filter(|(_, g)| g.op != Op::Constant) { writeln!(f, "{} -> {}", gate, name)?; } Ok(()) } } #[aoc(day24, part1)] pub fn part1(input: &str) -> u64 { let machine = parse(input); machine.actual_result() } #[aoc(day24, part2)] pub fn part2(input: &str) -> String { let mut machine = parse(input); let swaps = vec![("z06", "ksv"), ("nbd", "kbs"), ("z20", "tqq"), ("z39", "ckb")]; print!("before:\n{}", machine); for (a, b) in &swaps { machine.swap(a, b); } println!("after:\n{}", machine); println!("x : {:048b} ({0})", machine.register('x')); println!("y : {:048b} ({0})", machine.register('y')); println!("expected : {:048b} ({0})", machine.expected_result()); println!("actual : {:048b} ({0})", machine.actual_result()); let diff = machine.actual_result() ^ machine.expected_result(); println!("error : {diff:48b}"); let first_error = diff.trailing_zeros(); println!("first error at bit {first_error}"); let mut file = File::create("day24.dot").unwrap(); writeln!(file, "graph day24 {{").unwrap(); writeln!(file, " label=\"first error at bit {}\"", first_error); for (name, gate) in machine.gates { if gate.op != Op::Constant { for arg in gate.arguments { let color = match gate.op { Op::And => " [color=green]", Op::Or => " [color=blue]", Op::Xor => " [color=red]", _ => "", }; writeln!(file, "{} -- {} {};", name, arg, color); } } } writeln!(file, "}}"); // let mut test_machine = machine.clone(); // let mut swaps_left = 4; // while test_machine.actual_result() != test_machine.expected_result() { // let diff = machine.expected_result() ^ machine.actual_result(); // let our_first = diff.trailing_zeros(); // let a_candidates = machine.dependencies(format!("z{our_first:02}").as_str()); // for i in our_first+1..machine.out_bits { // let b_candidates = machine.dependencies(format!("z{i:02}").as_str()); // } // } let mut answer = swaps.into_iter().flat_map(|(a, b)| [a.to_string(), b.to_string()]).collect_vec(); answer.sort(); answer.iter().join(",") } #[cfg(test)] mod tests { use super::*; const EXAMPLE1: &str = "x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02"; const EXAMPLE2: &str = "x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj"; const EXAMPLE3: &str = "x00: 0 x01: 1 x02: 0 x03: 1 x04: 0 x05: 1 y00: 0 y01: 0 y02: 1 y03: 1 y04: 0 y05: 1 x00 AND y00 -> z05 x01 AND y01 -> z02 x02 AND y02 -> z01 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z00"; #[test] fn part1_example() { assert_eq!(part1(EXAMPLE1), 4); assert_eq!(part1(EXAMPLE2), 2024); } #[test] fn part2_example() { assert_eq!(part2(EXAMPLE3), "z00,z01,z02,z05"); } }