add day03 part1

This commit is contained in:
Stefan Schwarz 2021-12-04 02:47:23 +01:00
parent 1e95ecc760
commit 1618d5874f
3 changed files with 1069 additions and 0 deletions

View file

@ -18,3 +18,7 @@ path = "src/01.rs"
[[bin]] [[bin]]
name = "2" name = "2"
path = "src/02.rs" path = "src/02.rs"
[[bin]]
name = "3"
path = "src/03.rs"

65
src/03.rs Normal file
View file

@ -0,0 +1,65 @@
use std::iter::repeat;
static INPUT: &str = include_str!("03.txt");
fn main() {
part1(INPUT);
}
fn part1(input: &str) -> u32 {
let len = input
.lines()
.next()
.expect("must have at least one line")
.len();
let mut zeros: Vec<u32> = repeat(0).take(len).collect();
let mut ones: Vec<u32> = repeat(0).take(len).collect();
input.lines().for_each(|line| {
line.chars().enumerate().for_each(|(n, c)| match c {
'0' => zeros[n] += 1,
'1' => ones[n] += 1,
_ => unreachable!("invalid input"),
});
});
let gamma = ones.iter().zip(&zeros).fold(
0,
|acc, (a, b)| if a > b { (acc << 1) + 1 } else { acc << 1 },
);
let mask = (0..len).fold(0, |mask, _| (mask << 1) + 1);
let epsilon = !gamma & mask;
let result = gamma * epsilon;
println!("zeros: {:?}", zeros);
println!("ones: {:?}", ones);
println!("gamma: {}, epsilon: {:x}", gamma, epsilon);
println!("result: {}", result);
return result;
}
#[cfg(test)]
mod test {
#[test]
fn part1() {
let result = super::part1(
"
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
"
.trim(),
);
assert_eq!(result, 198);
}
}

1000
src/03.txt Normal file

File diff suppressed because it is too large Load diff