aboutsummaryrefslogtreecommitdiffstats
path: root/day01/solution.zig
diff options
context:
space:
mode:
Diffstat (limited to 'day01/solution.zig')
-rw-r--r--day01/solution.zig90
1 files changed, 90 insertions, 0 deletions
diff --git a/day01/solution.zig b/day01/solution.zig
new file mode 100644
index 0000000..6d15175
--- /dev/null
+++ b/day01/solution.zig
@@ -0,0 +1,90 @@
1const std = @import("std");
2const print = std.debug.print;
3const assert = std.debug.assert;
4const mem = std.mem;
5
6const fin = mem.trim(u8, @embedFile("./input.txt"), &std.ascii.whitespace);
7
8const digits_p1 = [_]u8{
9 '0',
10 '1',
11 '2',
12 '3',
13 '4',
14 '5',
15 '6',
16 '7',
17 '8',
18 '9',
19};
20
21const digits_p2 = [_][]const u8{
22 "0", "zero",
23 "1", "one",
24 "2", "two",
25 "3", "three",
26 "4", "four",
27 "5", "five",
28 "6", "six",
29 "7", "seven",
30 "8", "eight",
31 "9", "nine",
32};
33
34pub fn part1(comptime T: type, input: T) void {
35 var ans: u64 = 0;
36 var it = input;
37 while (it.next()) |line| {
38 const first = line[mem.indexOfAny(u8, line, &digits_p1) orelse continue] - '0';
39 const last = line[mem.lastIndexOfAny(u8, line, &digits_p1) orelse continue] - '0';
40 const n = 10 * first + last;
41
42 ans += n;
43 }
44
45 print("{d}\n", .{ans});
46}
47
48pub fn part2(comptime T: type, input: T) void {
49 var ans: u64 = 0;
50 var it = input;
51 while (it.next()) |line| {
52 var first: u64 = 0;
53 var last: u64 = 0;
54 var first_idx: i64 = 10000000;
55 var last_idx: i64 = -1;
56
57 for (digits_p2, 0..) |d, i| {
58 if (mem.indexOf(u8, line, d)) |t| {
59 const fi: i64 = @bitCast(t);
60 if (fi < first_idx) {
61 first_idx = fi;
62 first = i / 2;
63 }
64 }
65 if (mem.lastIndexOf(u8, line, d)) |t| {
66 const li: i64 = @bitCast(t);
67 if (li > last_idx) {
68 last_idx = li;
69 last = i / 2;
70 }
71 }
72 }
73 const n = 10 * first + last;
74
75 ans += n;
76 }
77
78 print("{d}\n", .{ans});
79}
80
81pub fn main() !void {
82 var gpa = std.heap.GeneralPurposeAllocator(.{}){};
83 defer _ = gpa.deinit();
84 var alloc = gpa.allocator();
85 _ = alloc;
86
87 const input = mem.splitScalar(u8, fin, '\n');
88 part1(@TypeOf(input), input);
89 part2(@TypeOf(input), input);
90}