use std::env; use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let args: Vec = env::args().collect(); if args.len() != 2 { eprintln!("Usage: {} filename", args[0]); std::process::exit(1); } let filename = &args[1]; let file = File::open(filename).unwrap_or_else(|_| panic!("No such file: {}", filename)); let reader = BufReader::new(file); let mut numbers: Vec = Vec::new(); for line in reader.lines() { let line = line.unwrap(); numbers.push(isize::from_str_radix(&line, 2).unwrap().try_into().unwrap()); } let mut co2_numbers: Vec = numbers.clone(); let mut oxygen: u32 = 0; let mut co2: u32 = 0; for bit in (0..12).rev() { let keep; let mut one_bits = 0; let mut zero_bits = 0; for num in &numbers { one_bits += (num >> bit) & 1; zero_bits += ((num >> bit) & 1) ^ 1; } println!("for bit: {}", bit); println!("one_bits: {}", one_bits); println!("zero_bits: {}", zero_bits); if zero_bits > one_bits { keep = 0; } else if zero_bits < one_bits { keep = 1; } else { keep = 1; } println!("keeping {}", keep); numbers.retain(|num| ((num >> bit) & 1) == keep); if numbers.len() == 1 { oxygen = numbers.pop().unwrap(); break; } println!("{:?}", numbers); } println!("====co2 now===="); for bit in (0..12).rev() { let keep; let mut one_bits = 0; let mut zero_bits = 0; for num in &co2_numbers { one_bits += (num >> bit) & 1; zero_bits += ((num >> bit) & 1) ^ 1; } println!("for bit: {}", bit); println!("one_bits: {}", one_bits); println!("zero_bits: {}", zero_bits); if zero_bits > one_bits { keep = 1; } else if zero_bits < one_bits { keep = 0; } else { keep = 0; } println!("keeping {}", keep); co2_numbers.retain(|num| (num >> bit) & 1 == keep); if co2_numbers.len() == 1 { co2 = co2_numbers.pop().unwrap(); break; } println!("{:?}", co2_numbers); } println!("oxygen: {}\nco2: {}", oxygen, co2); println!("answer: {}", oxygen * co2); }