#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] use std::env; use std::fs::File; use std::io::Read; #[derive(Debug, PartialEq, Clone)] struct Machine { ax: i128, ay: i128, bx: i128, by: i128, px: i128, py: i128, } fn solve(m: &Machine) -> Option { let mut min_price = None; for a in 0..100 { for b in 0..100 { let x = a * m.ax + b * m.bx; let y = a * m.ay + b * m.by; if x == m.px && y == m.py { let price = a * 3 + b * 1; if min_price == None || price < min_price.unwrap() { min_price = Some(price); } } } } min_price } fn solve2(m: &Machine) -> Option { let n1 = m.px * m.ay - m.py * m.ax; let n2 = m.bx * m.ay - m.by * m.ax; if n1 % n2 != 0 { return None; } let b = n1 / n2; let n1 = m.px - b * m.bx; let n2 = m.ax; if n1 % n2 != 0 { return None; } let a = n1 / n2; Some(a * 3 + b) } fn main() { let args: Vec = env::args().collect(); let filename = if args.len() == 1 { "in/".to_owned() + args[0].split('/').last().unwrap() + ".pzl" } else { args[1].clone() }; let mut f = File::open(filename).expect("cannot open file"); let mut content = String::new(); f.read_to_string(&mut content).expect("cannot read file"); let para = content.trim_end().split("\n\n"); let mut mvec: Vec = Vec::new(); for lines in para { let mut m: Machine = Machine { ax: 0, ay: 0, bx: 0, by: 0, px: 0, py: 0, }; let (s, rest) = lines.split_once("X+").unwrap(); let (s, rest) = rest.split_once(",").unwrap(); m.ax = s.parse().unwrap(); let (s, rest) = rest.split_once("Y+").unwrap(); let (s, rest) = rest.split_once("\n").unwrap(); m.ay = s.parse().unwrap(); let (s, rest) = rest.split_once("X+").unwrap(); let (s, rest) = rest.split_once(",").unwrap(); m.bx = s.parse().unwrap(); let (s, rest) = rest.split_once("Y+").unwrap(); let (s, rest) = rest.split_once("\n").unwrap(); m.by = s.parse().unwrap(); let (s, rest) = rest.split_once("X=").unwrap(); let (s, rest) = rest.split_once(",").unwrap(); m.px = s.parse().unwrap(); let (s, rest) = rest.split_once("Y=").unwrap(); m.py = rest.parse().unwrap(); mvec.push(m); } let mut res1 = 0; let mut res2 = 0; for m in &mvec { let p1 = solve(m); if let Some(val) = p1 { //println!("{}", val); res1 += val; } let m2: Machine = Machine { ax: m.ax, ay: m.ay, bx: m.bx, by: m.by, px: m.px + 10000000000000, py: m.py + 10000000000000, }; let p2 = solve2(&m2); if let Some(val) = p2 { //println!("{}", val); res2 += val; } } println!("res1: {}", res1); println!("res2: {}", res2); assert_eq!(res1, 29187); assert_eq!(res2, 99968222587852); }