day 3 part 1

This commit is contained in:
anna 2021-12-03 22:25:40 +01:00
parent 410a804172
commit 0d245f117b
Signed by: fef
GPG key ID: EC22E476DC2D3D84
4 changed files with 1071 additions and 0 deletions

View file

@ -11,4 +11,8 @@ path = "src/day01/main.rs"
name = "day02"
path = "src/day02/main.rs"
[[bin]]
name = "day03p1"
path = "src/day03p1/main.rs"
[dependencies]

View file

@ -10,4 +10,22 @@ I'm trying to solve everything using interesting algorithms, bit bangers, and si
highly optimized to tackle just the very specific problem at hand, rather than to come up with a
general solution.
## Running
My input files are in `input` and should be fed into the program's stdin.
For example, to run the challenge for day 2, type
```
cat input/day02.txt | cargo run day02
```
Starting from day 3, the individual challenges are further subdivided into part 1 and 2.
The input stays the same, but the binary name is `dayXXpY`:
```
cat input/day03.txt | cargo run day03p1
```
## License
Everything is released under the 2-Clause BSD License, which can be found in the `LICENSE` file.

1000
input/day03.txt Normal file

File diff suppressed because it is too large Load diff

49
src/day03p1/main.rs Normal file
View file

@ -0,0 +1,49 @@
use std::io;
fn main() {
let stdin = io::stdin();
let mut line_count = 0u32;
let mut bit_counts = [0u32; 32];
let mut num_bits = 0usize;
loop {
let mut buf = String::new();
match stdin.read_line(&mut buf).unwrap() {
0 => break,
_ => {
let numstr = buf.trim();
if line_count == 0 {
if numstr.len() > bit_counts.len() {
panic!("Only up to 32 bits supported");
}
num_bits = numstr.len();
} else if numstr.len() != num_bits {
panic!("Inconsistent number of bits");
}
line_count += 1;
let mut input = u32::from_str_radix(numstr, 2).unwrap();
for i in 0..num_bits {
bit_counts[i] += input & 1;
input >>= 1;
}
}
}
}
let line_count = line_count;
let bit_counts = bit_counts;
let mut gamma = 0u32;
for i in 0..num_bits {
let count = bit_counts[i];
println!("number of 1's in bit {}: {}", i, count);
if count > (line_count / 2) {
gamma |= 1 << i;
}
}
let epsilon = gamma ^ ((1 << num_bits) - 1);
println!("gamma = {}, epsilon = {}", gamma, epsilon);
println!("answer: {}", gamma * epsilon);
}