|
| 1 | +use crate::solutions::Solution; |
| 2 | +use itertools::Itertools; |
| 3 | +use std::str::FromStr; |
| 4 | + |
| 5 | +pub struct Day02; |
| 6 | + |
| 7 | +impl Solution for Day02 { |
| 8 | + fn part_one(&self, input: &str) -> String { |
| 9 | + self.parse(input) |
| 10 | + .map(|cuboid| cuboid.surface_area() + cuboid.smallest_side_area()) |
| 11 | + .sum::<u64>() |
| 12 | + .to_string() |
| 13 | + } |
| 14 | + |
| 15 | + fn part_two(&self, _input: &str) -> String { |
| 16 | + String::from("0") |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +impl Day02 { |
| 21 | + fn parse<'a>(&self, input: &'a str) -> impl Iterator<Item = RectangularCuboid> + 'a { |
| 22 | + input.lines().map(|line| line.parse().unwrap()) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +struct RectangularCuboid { |
| 27 | + width: u64, |
| 28 | + length: u64, |
| 29 | + height: u64, |
| 30 | +} |
| 31 | + |
| 32 | +impl RectangularCuboid { |
| 33 | + fn surface_area(&self) -> u64 { |
| 34 | + 2 * self.area_width_length() + 2 * self.area_width_height() + 2 * self.area_length_height() |
| 35 | + } |
| 36 | + |
| 37 | + fn smallest_side_area(&self) -> u64 { |
| 38 | + *[ |
| 39 | + self.area_width_length(), |
| 40 | + self.area_width_height(), |
| 41 | + self.area_length_height(), |
| 42 | + ] |
| 43 | + .iter() |
| 44 | + .min() |
| 45 | + .unwrap() |
| 46 | + } |
| 47 | + |
| 48 | + fn area_width_length(&self) -> u64 { |
| 49 | + self.width * self.length |
| 50 | + } |
| 51 | + |
| 52 | + fn area_width_height(&self) -> u64 { |
| 53 | + self.width * self.height |
| 54 | + } |
| 55 | + |
| 56 | + fn area_length_height(&self) -> u64 { |
| 57 | + self.length * self.height |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +impl FromStr for RectangularCuboid { |
| 62 | + type Err = String; |
| 63 | + |
| 64 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 65 | + let (width, length, height) = s |
| 66 | + .split_terminator('x') |
| 67 | + .map(|s| s.parse::<u64>().unwrap()) |
| 68 | + .collect_tuple() |
| 69 | + .unwrap(); |
| 70 | + |
| 71 | + Ok(Self { |
| 72 | + width, |
| 73 | + length, |
| 74 | + height, |
| 75 | + }) |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +#[cfg(test)] |
| 80 | +mod tests { |
| 81 | + use super::*; |
| 82 | + |
| 83 | + #[test] |
| 84 | + fn part_one_example_test() { |
| 85 | + assert_eq!("58", Day02.part_one("2x3x4")); |
| 86 | + assert_eq!("43", Day02.part_one("1x1x10")); |
| 87 | + } |
| 88 | +} |
0 commit comments