From: Greg Burri Date: Sun, 5 Dec 2021 22:55:27 +0000 (+0100) Subject: Day 3 part 1 X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=HEAD;p=advent_of_code_2021.git Day 3 part 1 --- diff --git a/Cargo.toml b/Cargo.toml index 5e26f12..81eeff7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "advent_of_code_2021" version = "0.1.0" authors = ["Greg Burri "] -edition = "2018" +edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src/day02.rs b/src/day02.rs index 732d179..cef65c3 100644 --- a/src/day02.rs +++ b/src/day02.rs @@ -22,7 +22,7 @@ pub fn parse_movements(movements: &str) -> Vec { "forward" => Movement::Forward(distance), "down" => Movement::Down(distance), "up" => Movement::Up(distance), - _ => Movement::Forward(0) + unknown_command => panic!("Unknown command: {}", unknown_command), } }) .collect() diff --git a/src/day03.rs b/src/day03.rs new file mode 100644 index 0000000..fff84d8 --- /dev/null +++ b/src/day03.rs @@ -0,0 +1,54 @@ +use std::iter::Iterator; + +type Diagnostic = Vec>; + +pub fn parse(diagnostic: &str) -> Diagnostic { + diagnostic + .split('\n') + .map(|line| { line.trim().chars().collect() }) + .collect() +} + +pub fn gamma_and_epsilon_rates(diagnostic: &Diagnostic) -> (u16, u16) { + let l = diagnostic[0].len(); + dbg!(l); + let mut gamma = 0u16; + for i in 0..l { + if diagnostic.iter().fold(0, |n, current| { n + if current[i] == '1' { 1 } else { 0 } }) > diagnostic.len() / 2 { + gamma |= 1; + } + + if i < l - 1 { + gamma <<= 1; + } + } + + (gamma, !gamma & 0xFFFFu16 >> (16 - l)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn part1() { + let diagnostic = + parse( + "00100 + 11110 + 10110 + 10111 + 10101 + 01111 + 00111 + 11100 + 10000 + 11001 + 00010 + 01010" + ); + let (gamma, epsilon) = gamma_and_epsilon_rates(&diagnostic); + assert_eq!(gamma, 22); + assert_eq!(epsilon, 9); + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index e3a099a..27fb5db 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ use std::time::Instant; mod common; mod day01; mod day02; +mod day03; fn day01() -> String { let report = common::read_list_of_numbers("data/day01.input", "\n"); @@ -17,6 +18,12 @@ fn day02() -> String { format!("part1: {}, part2: {}", final_position.horizontal * final_position.aim, final_position.horizontal * final_position.depth) } +fn day03() -> String { + let diagnostic = day03::parse(&fs::read_to_string("data/day03.input").unwrap()); + let (gamma, epsilon) = day03::gamma_and_epsilon_rates(&diagnostic); + format!("part1: {}, part2: {}", gamma as u32 * epsilon as u32, "") +} + fn format_micros(t: u128) -> String { if t < 10_000 { format!("{} μs", t) @@ -38,6 +45,7 @@ fn main() { let days: Vec String> = vec!( day01, day02, + day03, ); let args: Vec = env::args().skip(1).collect();