From: Ummon Date: Mon, 9 Dec 2019 21:20:31 +0000 (+0100) Subject: Day 08 part1 X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=646010fe88da845e2277106348c5fa552583cee3;p=advent_of_code_2019.git Day 08 part1 --- diff --git a/Cargo.toml b/Cargo.toml index c7438f7..7db3d01 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,4 +7,5 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -itertools = "0.8" \ No newline at end of file +itertools = "0.8" +image = "0.22" \ No newline at end of file diff --git a/src/day07.rs b/src/day07.rs index 77d8c48..e69de29 100644 --- a/src/day07.rs +++ b/src/day07.rs @@ -1 +0,0 @@ -fn fun() { } \ No newline at end of file diff --git a/src/day08.rs b/src/day08.rs index e69de29..074a632 100644 --- a/src/day08.rs +++ b/src/day08.rs @@ -0,0 +1,52 @@ +pub fn read_from_string(raw: &str) -> Vec { + raw.chars().map(|c| c.to_digit(10).unwrap() as u8).collect::>() +} + +pub fn decode_image(digits: &[u8], width: usize, height: usize) -> Vec> { + let nb_pixel = width * height; + let nb_layers = digits.len() / nb_pixel; + let mut layers: Vec> = Vec::new(); + for i in 0 .. nb_layers { + let layer: Vec = Vec::from(&digits[i * nb_pixel .. (i+1) * nb_pixel]); + layers.push(layer); + } + layers +} + +pub fn layer_with_fewer_0(layers: &[Vec]) -> &Vec { + let mut min = std::u32::MAX; + let mut layer_min = 0; + for i in 0 .. layers.len() { + let sum = layers[i].iter().fold(0, |sum, pix| if *pix == 0u8 { sum + 1 } else { sum }); + if sum < min { + min = sum; + layer_min = i; + } + } + &layers[layer_min] +} + +pub fn one_digits_times_two_digits(layer: &[u8]) -> i32 { + let (nb_1, nb_2) = + layer + .iter() + .fold( + (0, 0), + |(nb_1, nb_2), pix| + match *pix { 1u8 => (nb_1 + 1, nb_2), 2u8 => (nb_1, nb_2 + 1), _ => (nb_1, nb_2)} + ); + nb_1 * nb_2 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn part1() { + let raw = read_from_string("123456789012"); + let layers = decode_image(&raw, 3, 2); + let layer = layer_with_fewer_0(&layers[..]); + assert_eq!(one_digits_times_two_digits(layer), 1); + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 2c96367..470327b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -53,11 +53,16 @@ fn day07() -> String { } fn day08() -> String { - format!("") + let img = fs::read_to_string("data/day08.input").unwrap(); + + let raw = day08::read_from_string(&img); + let layers = day08::decode_image(&raw, 25, 6); + let layer = day08::layer_with_fewer_0(&layers[..]); + format!("part1: {}, part2: {}", day08::one_digits_times_two_digits(layer), 1) } fn day09() -> String { - let code = common::read_list_of_numbers("data/day09.input", ","); + let code = common::read_list_of_numbers::<&str, i64>("data/day09.input", ","); format!("part1: {:?}, part2: {:?}", day09::execute_op_code(&code, &[1]), day09::execute_op_code(&code, &[2])) }