diff --git a/day3/rust/src/main.rs b/day3/rust/src/main.rs index 45cf44a..04f380f 100644 --- a/day3/rust/src/main.rs +++ b/day3/rust/src/main.rs @@ -5,39 +5,80 @@ fn main() { let report: Vec<&str> = input.lines().collect(); let bit_count = report[0].len(); - let col_size = report.len(); - let mut gamma = 0; - let mut epsilon = 0; + { + // Part 1 + let col_size = report.len(); - for position in 0..bit_count { - gamma <<= 1; - epsilon <<= 1; + let mut gamma = 0; + let mut epsilon = 0; - let count = report - .iter() - .filter(|b| b.chars().nth(position).unwrap() == '1') - .count(); + for position in 0..bit_count { + gamma <<= 1; + epsilon <<= 1; - if count > col_size / 2 { - gamma += 1; - } else { - epsilon += 1; + let count = report + .iter() + .filter(|b| b.chars().nth(position).unwrap() == '1') + .count(); + + if count > col_size / 2 { + gamma += 1; + } else { + epsilon += 1; + } } + println!("Part 1: {}", gamma * epsilon); + } + + { + // Part 2 + let generator: i32 = { + let mut diagnostic = report.to_vec(); + + for position in 0..bit_count { + let col_size = diagnostic.len(); + let count = diagnostic + .iter() + .filter(|b| b.chars().nth(position).unwrap() == '1') + .count(); + + if count >= (col_size - count) { + diagnostic.retain(|b| b.chars().nth(position).unwrap() == '1'); + } else { + diagnostic.retain(|b| b.chars().nth(position).unwrap() == '0'); + } + + if diagnostic.len() == 1 { + break; + } + } + i32::from_str_radix(diagnostic[0], 2).unwrap() + }; + + let scrubber = { + let mut diagnostic = report.to_vec(); + + for position in 0..bit_count { + let col_size = diagnostic.len(); + let count = diagnostic + .iter() + .filter(|b| b.chars().nth(position).unwrap() == '0') + .count(); + + if count > (col_size - count) { + diagnostic.retain(|b| b.chars().nth(position).unwrap() == '1'); + } else { + diagnostic.retain(|b| b.chars().nth(position).unwrap() == '0'); + } + + if diagnostic.len() == 1 { + break; + } + } + i32::from_str_radix(diagnostic[0], 2).unwrap() + }; + + println!("Part 2: {}", generator * scrubber); } - println!("{}", gamma * epsilon); - // part1(input); - // part2(&commands); } - -// fn part1(report: String) { -// for i in 1..5 { -// let (ones, zeros): (Vec<&str>, Vec<&str>) = -// report.lines().partition(|l| l[i..l.len()].starts_with('1')); -// println!("{:?}", zeros); -// } -// } - -// fn part2(commands: &Vec<(&str, i32)>) { -// todo!(); -// }