Compare commits

...

2 Commits

Author SHA1 Message Date
Joseph Montanaro
b519e0bad2 day 3 part 1 2021-12-03 14:08:03 -08:00
Joseph Montanaro
335b7a25cf remove unnecessary lifetime 2021-12-03 12:23:08 -08:00
3 changed files with 40 additions and 4 deletions

View File

@ -19,7 +19,7 @@ struct MoveCmd {
}
impl<'a> FromStr for MoveCmd {
impl FromStr for MoveCmd {
type Err = eyre::Report;
fn from_str(s: &str) -> Result<Self, Self::Err> {

36
2021/src/day3.rs Normal file
View File

@ -0,0 +1,36 @@
use color_eyre::eyre;
pub fn part1(numbers: &Vec<u16>) -> u64 {
let mut bit_diffs: [isize; 12] = [0; 12];
for num in numbers {
for i in 0..11 {
if num & (1 << i) > 0 {
bit_diffs[i] += 1
}
else {
bit_diffs[i] -= 1
}
}
}
let mut gamma = 0u16;
for (i, sum) in bit_diffs.iter().enumerate() {
let bit = if *sum >= 0 {1} else {0};
gamma |= bit << i;
}
let epsilon = !gamma & (65535 >> 4); // since these are really only 12-bit numbers we have to clear the 4 spurious 1's that come from inverting epsilon
epsilon as u64 * gamma as u64
}
pub fn run(data: &str) -> eyre::Result<()> {
let mut nums = Vec::new();
for line in data.lines() {
nums.push(u16::from_str_radix(line, 2)?);
}
println!("One: {}", part1(&nums));
Ok(())
}

View File

@ -4,13 +4,13 @@ use color_eyre::eyre;
mod lib;
use lib::load;
mod day2;
mod day3;
fn main() -> eyre::Result<()> {
let data = load("data/02.txt")?;
let data = load("data/03.txt")?;
let start = Instant::now();
day2::run(&data)?;
day3::run(&data)?;
let (dur, unit) = format_ns(start.elapsed().as_nanos());
println!("Completed in {}{}", dur, unit);
Ok(())