Rename most_common -> column_sums

This commit is contained in:
Tyler Hallada 2021-12-03 17:21:46 -05:00
parent 18179dde06
commit 840f8547e8

View File

@ -3,29 +3,29 @@ use common::instrument;
const INPUT: &str = include_str!("input/input.txt"); const INPUT: &str = include_str!("input/input.txt");
fn get_most_common(lines: &[&str]) -> Vec<usize> { fn get_column_sums(lines: &[&str]) -> Vec<usize> {
let mut most_common = vec![0; lines[0].len()]; let mut column_sums = vec![0; lines[0].len()];
for line in lines.iter() { for line in lines.iter() {
let chars = line.chars(); let chars = line.chars();
for (i, c) in chars.enumerate() { for (i, c) in chars.enumerate() {
if c == '1' { if c == '1' {
most_common[i] += 1; column_sums[i] += 1;
} }
} }
} }
return most_common; return column_sums;
} }
fn solve_part1(input: &str) -> Result<i32> { fn solve_part1(input: &str) -> Result<i32> {
let lines: Vec<&str> = input.trim().lines().collect(); let lines: Vec<&str> = input.trim().lines().collect();
let most_common = get_most_common(&lines); let column_sums = get_column_sums(&lines);
let mut gamma = 0; let mut gamma = 0;
let mut epsilon = 0; let mut epsilon = 0;
for (i, c) in most_common.into_iter().enumerate() { for (i, c) in column_sums.into_iter().enumerate() {
if i > 0 { if i > 0 {
gamma <<= 1; gamma <<= 1;
epsilon <<= 1; epsilon <<= 1;
@ -46,23 +46,23 @@ fn solve_part2(input: &str) -> Result<i32> {
let mut oxygen = lines.clone(); let mut oxygen = lines.clone();
let mut co2 = lines.clone(); let mut co2 = lines.clone();
for i in 0..lines[0].len() { for col in 0..lines[0].len() {
let oxygen_most_common = get_most_common(&oxygen); let oxygen_column_sums = get_column_sums(&oxygen);
let co2_most_common = get_most_common(&co2); let co2_column_sums = get_column_sums(&co2);
if oxygen.len() > 1 { if oxygen.len() > 1 {
if oxygen_most_common[i] as f32 >= (oxygen.len() as f32 / 2.0) { if oxygen_column_sums[col] as f32 >= (oxygen.len() as f32 / 2.0) {
oxygen.retain(|l| l.chars().nth(i).unwrap() == '1'); oxygen.retain(|l| l.chars().nth(col).unwrap() == '1');
} else { } else {
oxygen.retain(|l| l.chars().nth(i).unwrap() == '0'); oxygen.retain(|l| l.chars().nth(col).unwrap() == '0');
} }
} }
if co2.len() > 1 { if co2.len() > 1 {
if co2_most_common[i] as f32 >= (co2.len() as f32 / 2.0) { if co2_column_sums[col] as f32 >= (co2.len() as f32 / 2.0) {
co2.retain(|l| l.chars().nth(i).unwrap() == '0'); co2.retain(|l| l.chars().nth(col).unwrap() == '0');
} else { } else {
co2.retain(|l| l.chars().nth(i).unwrap() == '1'); co2.retain(|l| l.chars().nth(col).unwrap() == '1');
} }
} }