finished december 3

This commit is contained in:
2021-12-04 22:22:43 +01:00
parent 15dc98a4bd
commit c69470afa5
2 changed files with 122 additions and 9 deletions

12
december_3/example.txt Normal file
View File

@@ -0,0 +1,12 @@
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010

View File

@@ -2,7 +2,7 @@ use std::fs::File;
use std::io::{BufReader};
use std::io::prelude::*;
const NUMBER_OF_BITS: u8 = 12;
const NUMBER_OF_BITS: u8 = 4; //12
fn main(){
let file = File::open("./input.txt").expect("Read failed");
@@ -12,6 +12,8 @@ fn main(){
//let mut gamma_bits = Vec::new();
let all_lines = reader.lines();
let mut most_common_val = Vec::new();
let mut least_common_val = Vec::new();
for line in all_lines{
@@ -24,25 +26,124 @@ fn main(){
let mut zeros = 0;
for l in &line_vec{
match l.chars().nth(i.into()).unwrap() {
'0' => zeros += 1,
'1' => ones += 1,
'0' => {
zeros += 1;
},
'1' => {
ones += 1;
},
_ => println!("you should never be here"),
}
}
if ones > zeros {
if zeros > ones {
print!("0");
most_common_val.push('0');
} else {
print!("1");
most_common_val.push('1');
}
if zeros > ones {
print!("1");
least_common_val.push('1');
} else {
print!("0");
least_common_val.push('0');
}
println!();
}
println!();
// 101001001011 2635
// 010110110100 1460
println!("Depth: {}, Horizontal: {}, Result: {}", 1,2,3);
//part 2
let mut result_vec = line_vec.to_owned();
let mut i: u8 = 0;
loop {
let mut temp_vec = Vec::new();
let most_common: char = get_most_common(i, &result_vec);
for l in &result_vec{
if most_common == l.chars().nth(i.into()).unwrap(){
let l_as_string = l.to_owned();
temp_vec.push(l_as_string);
}
}
if temp_vec.len() < 2 {
result_vec = temp_vec;
break;
}
i += 1;
result_vec = temp_vec;
}
println!("oxygen generator rating: {}", result_vec[0]);
let mut result_vec = line_vec.to_owned();
let mut i: u8 = 0;
loop {
let mut temp_vec = Vec::new();
let least_common: char = get_least_common(i, &result_vec);
for l in &result_vec{
if least_common == l.chars().nth(i.into()).unwrap(){
let l_as_string = l.to_owned();
temp_vec.push(l_as_string);
}
}
if temp_vec.len() < 2 {
result_vec = temp_vec;
break;
}
i += 1;
result_vec = temp_vec;
}
}
println!("co2 scrubber rating: {}", result_vec[0]);
}
// 101001001011 2635
// 010110110101 1461
// 2635 * 1461 = 3849735
fn get_most_common(bit: u8, in_vec:&Vec<String>) -> char {
let mut ones = 0;
let mut zeros = 0;
for l in in_vec{
match l.chars().nth(usize::from(bit)).unwrap() {
'0' => {
zeros += 1;
},
'1' => {
ones += 1;
},
_ => println!("you should never be here"),
}
}
if zeros > ones {
return '0';
} else {
return '1';
}
}
fn get_least_common(bit: u8, in_vec:&Vec<String>) -> char {
let mut ones = 0;
let mut zeros = 0;
for l in in_vec{
match l.chars().nth(usize::from(bit)).unwrap() {
'0' => {
zeros += 1;
},
'1' => {
ones += 1;
},
_ => println!("you should never be here"),
}
}
if zeros > ones {
return '1';
} else {
return '0';
}
}
//2735
//1501