-
Notifications
You must be signed in to change notification settings - Fork 0
/
03p1.odin
85 lines (75 loc) · 1.8 KB
/
03p1.odin
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
package main
import "core:fmt"
import "core:strconv"
import "core:strings"
D03P1 :: proc() {
input_string := #load("inputs/03.txt", string)
lines := strings.split(input_string, "\n", context.temp_allocator)
sum_of_multiplications := get_sum_of_multiplications(lines)
fmt.printf("Sum of all multiplications: %d\n", sum_of_multiplications)
}
get_sum_of_multiplications :: proc(lines: []string) -> int {
number_pairs := parse_corrupted_memory(lines)
defer delete(number_pairs)
sum := 0
for pair in number_pairs {
sum += pair[0] * pair[1]
}
return sum
}
parse_corrupted_memory :: proc(corrupted_memory: []string) -> (number_pairs: [dynamic][2]int) {
for line in corrupted_memory {
i := 0
for i < len(line) {
if line[i] == 'm' {
// Check for "mul("
if i + 3 < len(line) && line[i:i + 4] == "mul(" {
i += 4
num1, num2: int
ok: bool
i, num1, num2, ok = parse_multiplication(line, i)
if ok {
append(&number_pairs, [2]int{num1, num2})
}
} else {
i += 1
}
} else {
i += 1
}
}
}
return
}
parse_multiplication :: proc(
line: string,
start: int,
) -> (
new_pos: int,
num1: int,
num2: int,
ok: bool,
) {
// Parse first number
i := start
num_start := i
for i < len(line) && (line[i] >= '0' && line[i] <= '9') {
i += 1
}
if i == num_start {return i, 0, 0, false}
num1 = strconv.parse_int(line[num_start:i]) or_return
// Expect comma
if i >= len(line) || line[i] != ',' {return i, 0, 0, false}
i += 1
// Parse second number
num_start = i
for i < len(line) && (line[i] >= '0' && line[i] <= '9') {
i += 1
}
if i == num_start {return i, 0, 0, false}
num2 = strconv.parse_int(line[num_start:i]) or_return
// Expect closing parenthesis
if i >= len(line) || line[i] != ')' {return i, 0, 0, false}
i += 1
return i, num1, num2, true
}