-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathlib.rs
67 lines (60 loc) · 1.51 KB
/
lib.rs
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
use std::cmp::{Eq, PartialEq};
pub struct PartOne;
pub struct PartTwo;
#[derive(Debug, PartialEq, Eq)]
pub enum Instruction {
ADD,
MUL,
}
impl Instruction {
fn new(from: usize) -> Option<Instruction> {
match from {
1 => Some(Instruction::ADD),
2 => Some(Instruction::MUL),
_ => None,
}
}
}
pub fn compute(mut v: Vec<usize>) -> Option<usize> {
let mut cursor: usize = 0;
while let Some(i) = Instruction::new(v[cursor]) {
let index = v[cursor + 3];
v[index] = match i {
Instruction::ADD => v[v[cursor + 1]] + v[v[cursor + 2]],
Instruction::MUL => v[v[cursor + 1]] * v[v[cursor + 2]],
};
cursor += 4;
}
v.first().copied()
}
pub fn parse(input: &str) -> Vec<usize> {
input
.split(',')
.filter_map(|c| c.parse::<usize>().ok())
.collect::<Vec<usize>>()
}
impl aoclib::Solvable<&str, usize> for PartOne {
fn solve(input: &str) -> aoclib::Solution<usize> {
let mut v = parse(input);
v[1] = 12;
v[2] = 2;
compute(v).ok_or_else(|| aoclib::SolutionError::from("Not found"))
}
}
impl aoclib::Solvable<&str, usize> for PartTwo {
fn solve(input: &str) -> aoclib::Solution<usize> {
let vec = parse(input);
let target: usize = 19_690_720;
(0..=100)
.flat_map(|noun| (0..=100).map(move |verb| (noun, verb)))
.filter_map(|(noun, verb)| {
let mut v = vec.clone();
v[1] = noun;
v[2] = verb;
compute(v).map(|r| (noun, verb, r))
})
.find(|(_, _, r)| *r == target)
.map(|(noun, verb, _)| 100 * noun + verb)
.ok_or_else(|| aoclib::SolutionError::from("Not found"))
}
}