Added day 3 code for part 1 and 2

Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
This commit is contained in:
Louis Vallat 2021-12-04 01:12:20 +01:00
parent f420e96477
commit 3cd8684e2a
No known key found for this signature in database
GPG Key ID: 0C87282F76E61283
3 changed files with 1087 additions and 0 deletions

8
day3/Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "day2"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

1000
day3/input Normal file

File diff suppressed because it is too large Load Diff

79
day3/src/main.rs Normal file
View File

@ -0,0 +1,79 @@
use std::{fs, env, vec};
fn read_input(path: &str) -> String {
return fs::read_to_string(path).expect("Cannot read file.");
}
fn parse_input(s: &str) -> Vec<Vec<u32>> {
let mut r: Vec<Vec<u32>> = vec![];
for e in s.split("\n") {
if !e.is_empty() {
r.push(e.chars().filter_map(|e| e.to_digit(2)).collect());
}
}
return r;
}
fn bit_vec_to_u32(v: &Vec<u32>, invert: bool) -> u32 {
let mut acc = 0;
for i in 0..v.len() {
acc += if invert { (v[i] + 1) % 2 } else { v[i] } << (v.len() - 1 - i);
}
return acc;
}
fn get_most_in_col(v: &Vec<Vec<u32>>, c: usize) -> u32 {
let mut a = (0, 0);
for r in 0..v.len() {
if v[r][c] == 0 {
a.0 += 1;
} else {
a.1 += 1;
}
}
if a.1 == a.0 { return 1; }
else { return if a.1 > a.0 { 1 } else { 0 }; }
}
fn get_o2(v: &Vec<Vec<u32>>, c: usize) -> u32 {
if v.len() == 1 { return bit_vec_to_u32(&v[0], false); }
let a = get_most_in_col(&v, c);
let f = v.into_iter().filter(|e| e[c] == (a + 1) % 2)
.fold(vec![], |mut acc, e| { acc.push(e.to_owned()); return acc;});
return get_o2(&f, c + 1);
}
fn get_co2(v: &Vec<Vec<u32>>, c: usize) -> u32 {
if v.len() == 1 { return bit_vec_to_u32(&v[0], false); }
let a = get_most_in_col(&v, c);
let f = v.into_iter().filter(|e| e[c] == a)
.fold(vec![], |mut acc, e| { acc.push(e.to_owned()); return acc;});
return get_co2(&f, c + 1);
}
fn get_gamma_epsilon(v: &Vec<Vec<u32>>) -> (u32, u32) {
let mut acc: Vec<u32> = vec![];
for c in 0..v[0].len() {
acc.push(get_most_in_col(&v, c));
}
return (bit_vec_to_u32(&acc, false), bit_vec_to_u32(&acc, true));
}
fn main() {
let args: Vec<String> = env::args().collect();
for arg in args.iter().skip(1) {
let v = parse_input(&read_input(&arg));
let t = get_gamma_epsilon(&v);
let o = get_o2(&v, 0);
let c = get_co2(&v, 0);
println!("[{}]", arg);
println!("\tPart 1 : {} x {} = {}", t.0, t.1, t.0 * t.1);
println!("\tPart 2 : {} x {} = {}", o, c, o * c);
}
}