day24: i guess a part 1 solution

This commit is contained in:
ktims committed 2026-12-02 13:08:33 -07:00
1 parent 77fba87ef6
commit bb5f7f52f6
1 file changed
+179 -70
+179 -70
View File
@@ -1,10 +1,11 @@
use std::{borrow::BorrowMut, collections::VecDeque, fmt::Display, fs::File, io::Write, mem::swap};
use aoc_runner_derive::aoc; use aoc_runner_derive::aoc;
use itertools::Itertools; use itertools::Itertools;
use nom::And;
use regex::Regex; use regex::Regex;
use rustc_hash::FxHashMap; use rustc_hash::{FxHashMap, FxHashSet};
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Op { enum Op {
And, And,
Or, Or,
@@ -23,6 +24,17 @@ impl From<&str> for Op {
} }
} }
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)] #[derive(Clone, Debug)]
struct Gate { struct Gate {
op: Op, op: Op,
@@ -30,6 +42,12 @@ struct Gate {
arguments: [String; 2], 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 { impl Gate {
fn eval(&self, machine: &GateMachine) -> bool { fn eval(&self, machine: &GateMachine) -> bool {
match self.op { match self.op {
@@ -41,31 +59,85 @@ impl Gate {
} }
} }
#[derive(Debug)] #[derive(Clone, Debug)]
struct GateMachine { struct GateMachine {
gates: FxHashMap<String, Gate>, gates: FxHashMap<String, Gate>,
out_bits: usize,
} }
impl GateMachine { impl GateMachine {
fn val_of(&self, gate: &str) -> bool { fn val_of(&self, gate: &str) -> bool {
println!("gate: {}", gate);
if let Some(val) = self.gates[gate].value { if let Some(val) = self.gates[gate].value {
val val
} else { } else {
self.gates[gate].eval(self) 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::<usize>().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 { fn parse(input: &str) -> GateMachine {
let mut gates = FxHashMap::default(); let mut gates = FxHashMap::default();
for line in input.lines() { for line in input.lines() {
println!("{line}");
let const_re = Regex::new(r"^([xyz][0-9]{2}): ([01])$").unwrap(); 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(); 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) { if let Some(caps) = const_re.captures(line) {
println!(" is const: {:?}", caps);
gates.insert( gates.insert(
caps[1].to_string(), caps[1].to_string(),
Gate { Gate {
@@ -75,7 +147,6 @@ fn parse(input: &str) -> GateMachine {
}, },
); );
} else if let Some(caps) = gate_re.captures(line) { } else if let Some(caps) = gate_re.captures(line) {
println!(" is gate: {:?}", caps);
gates.insert( gates.insert(
caps[4].to_string(), caps[4].to_string(),
Gate { Gate {
@@ -86,26 +157,90 @@ fn parse(input: &str) -> GateMachine {
); );
} }
} }
GateMachine { gates } let out_bits = gates
.iter()
.filter(|(k, _)| k.starts_with('z'))
.map(|(k, _)| k.split_at(1).1.parse::<u64>().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)] #[aoc(day24, part1)]
pub fn part1(input: &str) -> i64 { pub fn part1(input: &str) -> u64 {
let machine = parse(input); let machine = parse(input);
let z_gates = machine machine.actual_result()
.gates
.keys()
.filter(|k| k.starts_with('z'))
.map(|s| (s, s.split_at(1).1.parse::<usize>().unwrap()));
let bit_vals = z_gates
.map(|(name, bit)| if machine.val_of(name) { 1 << bit } else { 0 })
.fold(0, |accum, val| accum | val);
bit_vals
} }
#[aoc(day24, part2)] #[aoc(day24, part2)]
pub fn part2(input: &str) -> i64 { pub fn part2(input: &str) -> String {
0 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)] #[cfg(test)]
@@ -119,53 +254,7 @@ y01: 1
y02: 0 y02: 0
x00 AND y00 -> z00 x00 AND y00 -> z00
x01 XOR y01 -> z01x00: 1 x01 XOR y01 -> z01
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
x02 OR y02 -> z02"; x02 OR y02 -> z02";
const EXAMPLE2: &str = "x00: 1 const EXAMPLE2: &str = "x00: 1
@@ -216,6 +305,26 @@ hwm AND bqk -> z03
tgd XOR rvg -> z12 tgd XOR rvg -> z12
tnw OR pbm -> gnj"; 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] #[test]
fn part1_example() { fn part1_example() {
assert_eq!(part1(EXAMPLE1), 4); assert_eq!(part1(EXAMPLE1), 4);
@@ -224,6 +333,6 @@ tnw OR pbm -> gnj";
#[test] #[test]
fn part2_example() { fn part2_example() {
assert_eq!(part2(EXAMPLE1), 0); assert_eq!(part2(EXAMPLE3), "z00,z01,z02,z05");
} }
} }