1
0
mirror of https://gitlab.com/MisterBiggs/aoc2021.git synced 2025-06-15 22:46:51 +00:00
AoC2021/src/day3.rs

86 lines
2.4 KiB
Rust

use std::fs;
pub fn run() {
println!("Day 3:");
let input = fs::read_to_string("./inputs/day3.txt").expect("Could not read file");
let report: Vec<&str> = input.lines().collect();
let bit_count = report[0].len();
{
// Part 1
let col_size = report.len();
let mut gamma = 0;
let mut epsilon = 0;
for position in 0..bit_count {
gamma <<= 1;
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!("\tPart 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!("\tPart 2: {}", generator * scrubber);
}
}