-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday4.c3
More file actions
76 lines (72 loc) · 2.25 KB
/
Copy pathday4.c3
File metadata and controls
76 lines (72 loc) · 2.25 KB
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
/*
* Advent of Code 2024 day 4
* Sample solution demonstrating C3 language and standard library.
*/
import std::io, std::time, std::collections;
fn int? solve1(List{String} lines)
{
int matches = 0;
sz line_max = lines[0].len - 3;
sz lines_max = lines.len() - 3;
foreach (y, line : lines)
{
foreach (x, c : line)
{
if (c != 'X') continue;
if (x > 2 && line[x - 3:3] == "SAM") matches++;
if (x < line_max && line[x + 1:3] == "MAS") matches++;
if (y > 2)
{
if (lines[y - 1][x] == 'M' && lines[y - 2][x] == 'A' && lines[y - 3][x] == 'S') matches++;
if (x > 2 && lines[y - 1][x - 1] == 'M' && lines[y - 2][x - 2] == 'A' && lines[y - 3][x - 3] == 'S') matches++;
if (x < line_max && lines[y - 1][x + 1] == 'M' && lines[y - 2][x + 2] == 'A' && lines[y - 3][x + 3] == 'S') matches++;
}
if (y < lines_max)
{
if (lines[y + 1][x] == 'M' && lines[y + 2][x] == 'A' && lines[y + 3][x] == 'S') matches++;
if (x > 2 && lines[y + 1][x - 1] == 'M' && lines[y + 2][x - 2] == 'A' && lines[y + 3][x - 3] == 'S') matches++;
if (x < line_max && lines[y + 1][x + 1] == 'M' && lines[y + 2][x + 2] == 'A' && lines[y + 3][x + 3] == 'S') matches++;
}
}
}
return matches;
}
macro bool is_valid_pair(char a, char b)
{
return (a == 'M' && b == 'S') || (a == 'S' && b == 'M');
}
fn int? solve2(List{String} lines)
{
int matches = 0;
sz last_x = lines[0].len - 1;
sz last_y = lines.len() - 1;
foreach (y, line : lines)
{
if (y == 0 || y == last_y) continue;
foreach (x, c : line)
{
if (x == 0 || x == last_x) continue;
if (c != 'A') continue;
if (!is_valid_pair(lines[y - 1][x - 1], lines[y + 1][x + 1])) continue;
if (!is_valid_pair(lines[y + 1][x - 1], lines[y - 1][x + 1])) continue;
matches++;
}
}
return matches;
}
fn void main()
{
io::printn("Advent of code, day 4.");
@pool()
{
List{String} lines;
lines.tinit();
File f = file::open("day4.txt", "rb")!!;
defer (void)f.close();
while (try line = io::treadline(&f)) lines.push(line);
// Simple benchmarking with Clock, "mark" returns the last duraction and resets the clock
Clock c = clock::now();
io::printfn("* Task 1: %d - completed in %s", solve1(lines)!!, c.mark());
io::printfn("* Task 2: %d - completed in %s", solve2(lines)!!, c.mark());
};
}