From 4fadfc81d701dcbe90398a8dddedd3e2dc16277c Mon Sep 17 00:00:00 2001 From: Philippe Zwietering Date: Sun, 12 Dec 2021 23:59:56 +0100 Subject: [PATCH] Fixed bugs in part 2 of 3, mcb and lcb were not determined correctly --- advent_of_code/3.rs | 51 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/advent_of_code/3.rs b/advent_of_code/3.rs index ddfd85a..9f89eee 100644 --- a/advent_of_code/3.rs +++ b/advent_of_code/3.rs @@ -98,27 +98,39 @@ fn main(){ let mut n_scrubber = line_numbers; for bit_n in 0 .. b_len { + let mcb = most_common_bit(bit_n, &viable_oxygen, &diagnostics); + let lcb = !most_common_bit(bit_n, &viable_scrubber, &diagnostics); + for line_n in 0 .. line_numbers { if viable_oxygen[line_n] && n_oxygen > 1 { - if diagnostics[line_n][bit_n] != gamma_rate[bit_n] { + if diagnostics[line_n][bit_n] != mcb { n_oxygen -= 1; viable_oxygen[line_n] = false; } } if viable_scrubber[line_n] && n_scrubber > 1 { - if diagnostics[line_n][bit_n] == gamma_rate[bit_n] { + if diagnostics[line_n][bit_n] != lcb { n_scrubber -= 1; viable_scrubber[line_n] = false; } } } + // println!("\nIteration {}:", bit_n); + // for line_n in 0 .. line_numbers { + // if viable_oxygen[line_n] { + // print_bool_vec(&diagnostics[line_n]); + // } + // } + if n_oxygen == 1 && n_scrubber == 1 { break; } } + // println!("n_oxygen: {}, n_scrubber: {}", n_oxygen, n_scrubber); + let mut oxygen_ans = 0; let mut scrubber_ans = 0; @@ -132,6 +144,9 @@ fn main(){ } } + print_bool_vec(&diagnostics[oxygen_ans]); + // print_bool_vec(&diagnostics[scrubber_ans]); + diagnostics[oxygen_ans].reverse(); diagnostics[scrubber_ans].reverse(); @@ -155,4 +170,36 @@ fn bit_to_decimal(bits: &Vec::) -> u64 { } return result; +} + +fn most_common_bit(index: usize, valid_series: &Vec::, bit_series: &Vec::>) -> bool { + let mut ones = 0; + let mut valids = 0; + + for i in 0 .. valid_series.len() { + if valid_series[i] { + valids += 1; + + if bit_series[i][index] { + ones += 1; + } + } + } + + let mut v = valids as f32; + v /= 2.0; + v = v.ceil(); + valids = v as u64; + + if ones >= valids { + return true; + } + + return false; +} + +fn print_bool_vec(input: &Vec::) -> () { + for b in input { + print!("{},", b); + } println!(); } \ No newline at end of file