Advertisement
saaoijeefhiuh

2024 day 17

Dec 17th, 2024 (edited)
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.72 KB | None | 0 0
  1. pub fn part_two(input: &str) -> Option<u64> {
  2.     let inst: Vec<u8> = parse(input).1;
  3.  
  4.     fn solve(inst: &Vec<u8>, pos: usize, a: u64) -> bool {
  5.         let mut reg: Vec<u64> = vec![a, 0, 0];
  6.         for p in 0..(inst.len() / 2) {
  7.             let operand = inst[p * 2 + 1] as u64;
  8.  
  9.             match OpCode::from_u8(inst[p * 2]) {
  10.                 OpCode::Adv => reg[0] >>= combo(operand, &reg),
  11.                 OpCode::Bxl => reg[1] ^= operand,
  12.                 OpCode::Bst => reg[1] = combo(operand, &reg) % 8,
  13.                 OpCode::Jnz => return solve(inst, pos + 1, reg[0]),
  14.                 OpCode::Bxc => reg[1] ^= reg[2],
  15.                 OpCode::Out if ((combo(operand, &reg) % 8) as u8) != inst[pos] => return false,
  16.                 OpCode::Out if pos == (inst.len() - 1) => return true,
  17.                 OpCode::Out => {}
  18.                 OpCode::Bdv => reg[1] = reg[0] >> combo(operand, &reg),
  19.                 OpCode::Cdv => reg[2] = reg[0] >> combo(operand, &reg),
  20.             }
  21.         }
  22.  
  23.         false
  24.     }
  25.  
  26.     let mut search: Vec<u64> = vec![0];
  27.  
  28.     // progressively search for solution to each output in reverse
  29.     for target in (0..inst.len()).rev() {
  30.         println!("{:?}", search);
  31.         let mut next: Vec<u64> = Vec::new();
  32.         // 8 possible values of RegA could generate this, so check them
  33.         for a in search.iter().flat_map(|a| (0..8).map(move |i| a + i)) {
  34.             if solve(&inst, target, a) {
  35.                 // this value of RegA produces the last N values
  36.                 if target == 0 {
  37.                     // done!
  38.                     return Some(a);
  39.                 }
  40.                 next.push(a << 3);
  41.             }
  42.         }
  43.         search = next;
  44.     }
  45.  
  46.     None
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement