DEVELOPMENT ENVIRONMENT

~liljamo/aoc2024

ref: 98f77e7ed7c9592aa066ce4a614b17dc9e1ddf18 aoc2024/src/day7/mod.rs -rw-r--r-- 4.7 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use std::{
    fs::File,
    io::{BufRead, BufReader},
    path::Path,
    str::FromStr,
};

pub fn solve(input: &Path) -> anyhow::Result<()> {
    println!("part one: {}", part_one(input)?);
    println!("part two: {}", part_two(input)?);

    Ok(())
}

#[derive(Debug)]
struct Equation {
    answer: u64,
    inputs: Vec<u64>,
}

impl FromStr for Equation {
    type Err = Box<dyn std::error::Error>;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parts = s.split(":");

        Ok(Equation {
            answer: parts.next().unwrap().parse()?,
            inputs: parts
                .next()
                .unwrap()
                .split_whitespace()
                .map(|n| -> u64 { n.parse().unwrap() })
                .collect(),
        })
    }
}

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

    let mut equations = vec![];
    for line in reader.lines() {
        equations.push(Equation::from_str(&line?).unwrap());
    }

    Ok(equations
        .iter()
        .filter(|eq| check_equation_one(eq))
        .map(|eq| eq.answer)
        .collect::<Vec<u64>>()
        .iter()
        .sum())
}

fn check_equation_one(eq: &Equation) -> bool {
    let positions = eq.inputs.len() - 1;

    if positions == 1 {
        if eq.inputs[0] + eq.inputs[1] == eq.answer {
            return true;
        }
        if eq.inputs[0] * eq.inputs[1] == eq.answer {
            return true;
        }
        return false;
    }

    let operators = ["+", "*"];

    let combinations: Vec<String> = (operators.len()..positions).fold(
        operators
            .iter()
            .flat_map(|c| operators.iter().map(move |&d| d.to_owned() + *c))
            .collect(),
        |a, _| {
            a.into_iter()
                .flat_map(|c| operators.iter().map(move |&d| d.to_owned() + &*c))
                .collect()
        },
    );

    for combination in combinations {
        let combination: Vec<char> = combination.chars().collect();
        let mut current: Option<u64> = None;
        for (i, input) in eq.inputs.iter().enumerate() {
            if current.is_none() {
                current = Some(*input);
                continue;
            }

            match combination[i - 1] {
                '+' => current = Some(current.unwrap() + input),
                '*' => current = Some(current.unwrap() * input),
                _ => panic!(),
            }
        }
        if current.unwrap() == eq.answer {
            return true;
        }
    }

    false
}

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

    let mut equations = vec![];
    for line in reader.lines() {
        equations.push(Equation::from_str(&line?).unwrap());
    }

    Ok(equations
        .iter()
        .filter(|eq| check_equation_two(eq))
        .map(|eq| eq.answer)
        .collect::<Vec<u64>>()
        .iter()
        .sum())
}

fn check_equation_two(eq: &Equation) -> bool {
    let positions = eq.inputs.len() - 1;

    if positions == 1 {
        if eq.inputs[0] + eq.inputs[1] == eq.answer {
            return true;
        }
        if eq.inputs[0] * eq.inputs[1] == eq.answer {
            return true;
        }
        if (eq.inputs[0].to_string() + &eq.inputs[1].to_string())
            .parse::<u64>()
            .unwrap()
            == eq.answer
        {
            return true;
        }
        return false;
    }

    let operators = ["+", "*", "|"];

    let combinations: Vec<String> = (operators.len()..positions + 1).fold(
        operators
            .iter()
            .flat_map(|c| operators.iter().map(move |&d| d.to_owned() + *c))
            .collect(),
        |a, _| {
            a.into_iter()
                .flat_map(|c| operators.iter().map(move |&d| d.to_owned() + &*c))
                .collect()
        },
    );

    for combination in combinations {
        let combination: Vec<char> = combination.chars().collect();
        let mut current: Option<u64> = None;
        for (i, input) in eq.inputs.iter().enumerate() {
            if current.is_none() {
                current = Some(*input);
                continue;
            }

            match combination[i - 1] {
                '+' => current = Some(current.unwrap() + input),
                '*' => current = Some(current.unwrap() * input),
                '|' => {
                    current = Some(
                        (current.unwrap().to_string() + &input.to_string())
                            .parse()
                            .unwrap(),
                    )
                }
                _ => panic!(),
            }
        }
        if current.unwrap() == eq.answer {
            return true;
        }
    }

    false
}