year2015/
day21.rs

1use utils::prelude::*;
2
3/// RPG item shop combinations.
4#[derive(Clone, Debug)]
5pub struct Day21 {
6    part1: u32,
7    part2: u32,
8}
9
10const WEAPONS: [(u32, u32); 5] = [(8, 4), (10, 5), (25, 6), (40, 7), (74, 8)];
11const ARMOR: [(u32, u32); 6] = [(0, 0), (13, 1), (31, 2), (53, 3), (75, 4), (102, 5)];
12const RINGS: [(u32, u32, u32); 8] = [
13    (0, 0, 0),
14    (0, 0, 0),
15    (25, 1, 0),
16    (50, 2, 0),
17    (100, 3, 0),
18    (20, 0, 1),
19    (40, 0, 2),
20    (80, 0, 3),
21];
22
23impl Day21 {
24    pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
25        let (boss_health, boss_damage, boss_armor) = parser::u32()
26            .with_prefix("Hit Points: ")
27            .then(parser::u32().with_prefix("\nDamage: "))
28            .then(parser::u32().with_prefix("\nArmor: "))
29            .parse_complete(input)?;
30
31        let mut min_gold_win = u32::MAX;
32        let mut max_gold_loss = 0;
33        for weapon in WEAPONS {
34            for armor in ARMOR {
35                for (i, &ring1) in RINGS.iter().enumerate() {
36                    for &ring2 in &RINGS[i + 1..] {
37                        let gold = weapon.0 + armor.0 + ring1.0 + ring2.0;
38                        let player_damage = weapon.1 + ring1.1 + ring2.1;
39                        let player_armor = armor.1 + ring1.2 + ring2.2;
40
41                        let player_deals = player_damage.saturating_sub(boss_armor).max(1);
42                        let turn_boss_dies = boss_health.div_ceil(player_deals);
43
44                        let boss_deals = boss_damage.saturating_sub(player_armor).max(1);
45                        let turn_player_dies = 100u32.div_ceil(boss_deals);
46
47                        if turn_boss_dies <= turn_player_dies {
48                            min_gold_win = min_gold_win.min(gold);
49                        } else {
50                            max_gold_loss = max_gold_loss.max(gold);
51                        }
52                    }
53                }
54            }
55        }
56
57        Ok(Self {
58            part1: min_gold_win,
59            part2: max_gold_loss,
60        })
61    }
62
63    #[must_use]
64    pub fn part1(&self) -> u32 {
65        self.part1
66    }
67
68    #[must_use]
69    pub fn part2(&self) -> u32 {
70        self.part2
71    }
72}
73
74examples!(Day21 -> (u32, u32) []);