|
| 1 | +use std::fs; |
| 2 | +use std::cmp::min; |
| 3 | + |
| 4 | +struct Gift { length: u64, width: u64, height: u64 } |
| 5 | +impl Gift { |
| 6 | + /// Create a Gift object from a String |
| 7 | + fn from_string(string: &String) -> Self { |
| 8 | + let mut factors = string.trim().split("x").map(|num| { |
| 9 | + num.parse::<u64>().unwrap() |
| 10 | + }); |
| 11 | + let (length, width, height) = ( |
| 12 | + factors.next().unwrap(), |
| 13 | + factors.next().unwrap(), |
| 14 | + factors.next().unwrap() |
| 15 | + ); |
| 16 | + if factors.next().is_some() { |
| 17 | + panic!("Invalid gift specification"); |
| 18 | + } |
| 19 | + Self { length, width, height } |
| 20 | + } |
| 21 | + |
| 22 | + /// The full surface area of the gift |
| 23 | + fn area(&self) -> u64 { |
| 24 | + (2 * self.length * self.width) |
| 25 | + + (2 * self.width * self.height) |
| 26 | + + (2 * self.length * self.height) |
| 27 | + } |
| 28 | + |
| 29 | + /// The overhead of packing paper used when packing the gift |
| 30 | + fn packing_overhead(&self) -> u64 { |
| 31 | + min( |
| 32 | + min(self.length * self.width, self.width * self.height), |
| 33 | + self.length * self.height |
| 34 | + ) |
| 35 | + } |
| 36 | + |
| 37 | + /// The volume of the box (for ribbon bows) |
| 38 | + fn volume(&self) -> u64 { |
| 39 | + self.length * self.width * self.height |
| 40 | + } |
| 41 | + |
| 42 | + /// Perimeter of the smallest side |
| 43 | + fn perimeter(&self) -> u64 { |
| 44 | + min( |
| 45 | + min( |
| 46 | + (2 * self.length) + (2 * self.width), |
| 47 | + (2 * self.width) + (2 * self.height) |
| 48 | + ), |
| 49 | + (2 * self.length) + (2 * self.height) |
| 50 | + ) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +fn read_input(filename: &str) -> Vec<String> { |
| 55 | + if let Ok(input_text) = fs::read_to_string(filename) { |
| 56 | + input_text |
| 57 | + .trim() |
| 58 | + .split("\n") |
| 59 | + .map(|line| line.trim().to_owned()) |
| 60 | + .collect() |
| 61 | + } else { |
| 62 | + panic!("Unable to read input from file: {}", filename); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +pub fn main() { |
| 67 | + let gifts = read_input("day02.in").iter() |
| 68 | + .map(Gift::from_string).collect::<Vec<Gift>>(); |
| 69 | + |
| 70 | + let solution1 = gifts.iter() |
| 71 | + .map(|gift| gift.area() + gift.packing_overhead()) |
| 72 | + .fold(0, |accumulator, packing_paper| accumulator + packing_paper); |
| 73 | + let solution2 = gifts.iter() |
| 74 | + .map(|gift| gift.perimeter() + gift.volume()) |
| 75 | + .fold(0, |accumulator, ribbon| accumulator + ribbon); |
| 76 | + |
| 77 | + println!("Part 1: {}\nPart 2: {}", solution1, solution2); |
| 78 | +} |
0 commit comments