1
0
Fork 0
This commit is contained in:
Lars Martens 2021-12-03 17:04:06 +01:00
parent 7c9e4a2da1
commit 32c08e1fe9
4 changed files with 1087 additions and 1 deletions

12
input/03-test.txt Normal file
View file

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

1000
input/03.txt Normal file

File diff suppressed because it is too large Load diff

View file

@ -26,4 +26,4 @@ fn input() -> impl Iterator<Item = i32> {
include_str!("../../input/01a.txt")
.lines()
.map(|l| l.parse().unwrap())
}
}

74
src/bin/03.rs Normal file
View file

@ -0,0 +1,74 @@
fn main() {
let gamma_bits = gamma(&input());
let gamma = to_dec(&gamma_bits);
let epsilon = to_dec(&invert(&gamma_bits));
println!(
"First solution: gamma={}, epsilon={}, product={}",
gamma,
epsilon,
gamma * epsilon
);
let oxygen = to_dec(&life_support(input(), false));
let co2 = to_dec(&life_support(input(), true));
println!(
"Second solution: oxygen={}, co2={}, product={}",
oxygen,
co2,
oxygen * co2
);
}
type Binary = Vec<i32>;
fn life_support(mut it: Vec<Binary>, co2: bool) -> Binary {
let mut i = 0;
while it.len() > 1 {
let gamma = gamma(&it);
it = it
.into_iter()
.filter(|b| b[i] == gamma[i] ^ co2 as i32)
.collect();
i += 1;
}
it.remove(0)
}
fn to_dec(b: &Binary) -> i32 {
let mut acc = 0;
for (i, n) in b.iter().rev().copied().enumerate() {
acc |= n << i;
}
acc
}
fn invert(b: &Binary) -> Binary {
b.iter().map(|&n| n ^ 1).collect()
}
/// gamma returns a pattern of the most common bits for each position.
fn gamma(it: &Vec<Binary>) -> Binary {
let mut iter = it.clone().into_iter();
let mut acc = iter.next().unwrap();
for n in iter {
for i in 0..acc.len() {
acc[i] += 2 * n[i] - 1;
}
}
for i in 0..acc.len() {
acc[i] = (acc[i] > 0) as i32;
}
acc
}
/// several lines, each line has several digits
fn input() -> Vec<Binary> {
include_str!("../../input/03.txt")
.lines()
.map(|l| l.chars().map(|c| c.to_digit(2).unwrap() as i32).collect())
.collect()
}