-
Notifications
You must be signed in to change notification settings - Fork 9
/
day03.rs
82 lines (69 loc) · 1.86 KB
/
day03.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//! # Mull It Over
//!
//! Solves both parts simultaneously using a custom parser instead of
//! [regex](https://en.wikipedia.org/wiki/Regular_expression).
type Input = (u32, u32);
pub fn parse(input: &str) -> Input {
let memory = input.as_bytes();
let mut index = 0;
let mut enabled = true;
let mut part_one = 0;
let mut part_two = 0;
while index < memory.len() {
// Skip junk characters
if memory[index] != b'm' && memory[index] != b'd' {
index += 1;
continue;
}
// Check possible prefixes
if memory[index..].starts_with(b"mul(") {
index += 4;
} else if memory[index..].starts_with(b"do()") {
index += 4;
enabled = true;
continue;
} else if memory[index..].starts_with(b"don't()") {
index += 7;
enabled = false;
continue;
} else {
index += 1;
continue;
}
// First number
let mut first = 0;
while memory[index].is_ascii_digit() {
first = 10 * first + (memory[index] - b'0') as u32;
index += 1;
}
// First delimiter
if memory[index] != b',' {
continue;
}
index += 1;
// Second number
let mut second = 0;
while memory[index].is_ascii_digit() {
second = 10 * second + (memory[index] - b'0') as u32;
index += 1;
}
// Second delimiter
if memory[index] != b')' {
continue;
}
index += 1;
// Multiply
let product = first * second;
part_one += product;
if enabled {
part_two += product;
}
}
(part_one, part_two)
}
pub fn part1(input: &Input) -> u32 {
input.0
}
pub fn part2(input: &Input) -> u32 {
input.1
}