DEVELOPMENT ENVIRONMENT

~liljamo/aoc2024

ref: 98f77e7ed7c9592aa066ce4a614b17dc9e1ddf18 aoc2024/src/day13/part1.rs -rw-r--r-- 2.4 KiB
98f77e7eJonni Liljamo feat: day13 a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use std::{
    fs::File,
    io::{BufRead, BufReader},
    path::Path,
};

#[derive(Debug)]
struct M {
    a: P,
    b: P,
    p: P,
}

impl M {
    fn from_lines(lines: &[String]) -> Self {
        let a_line = &lines[0];
        let b_line = &lines[1];
        let p_line = &lines[2];

        Self {
            a: P {
                x: a_line[&a_line.find("X").unwrap() + 2..a_line.find(",").unwrap()]
                    .parse()
                    .unwrap(),
                y: a_line[&a_line.find("Y").unwrap() + 2..a_line.len()]
                    .parse()
                    .unwrap(),
            },
            b: P {
                x: b_line[&b_line.find("X").unwrap() + 2..b_line.find(",").unwrap()]
                    .parse()
                    .unwrap(),
                y: b_line[&b_line.find("Y").unwrap() + 2..b_line.len()]
                    .parse()
                    .unwrap(),
            },
            p: P {
                x: p_line[&p_line.find("X").unwrap() + 2..p_line.find(",").unwrap()]
                    .parse()
                    .unwrap(),
                y: p_line[&p_line.find("Y").unwrap() + 2..p_line.len()]
                    .parse()
                    .unwrap(),
            },
        }
    }
}

#[derive(Debug)]
struct P {
    x: usize,
    y: usize,
}

pub fn part_one(input: &Path) -> anyhow::Result<usize> {
    let reader = BufReader::new(File::open(input)?);

    let machines: Vec<M> = reader
        .lines()
        .filter_map(|l| {
            let l = l.unwrap();
            if !l.is_empty() {
                Some(l)
            } else {
                None
            }
        })
        .collect::<Vec<String>>()
        .chunks(3)
        .map(|l| -> M { M::from_lines(l) })
        .collect();

    let mut answer = 0;
    for machine in machines {
        let mut oks: Vec<usize> = vec![];
        let (mut x, mut y) = (0, 0);
        'a: for a in 1..101 {
            x += machine.a.x;
            y += machine.a.y;
            let (mut x, mut y) = (x, y);
            for b in 1..101 {
                x += machine.b.x;
                y += machine.b.y;
                if x == machine.p.x && y == machine.p.y {
                    oks.push(a * 3 + b);
                    continue 'a;
                }
            }
        }
        if !oks.is_empty() {
            oks.sort();
            answer += oks.first().unwrap();
        }
    }

    Ok(answer)
}