From 3c97ec63d921c7d2f132a834f9b739cc8d039c99 Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Fri, 10 Dec 2021 19:54:01 +0300 Subject: 2021, day3: done --- 2021/day3/src/main.rs | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 2021/day3/src/main.rs (limited to '2021/day3/src') diff --git a/2021/day3/src/main.rs b/2021/day3/src/main.rs new file mode 100644 index 0000000..2440a39 --- /dev/null +++ b/2021/day3/src/main.rs @@ -0,0 +1,99 @@ +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); +} -- cgit v1.2.3-70-g09d2