1const std = @import("std");
2
3pub fn pt1(input: []const u8) u64 {
4 var counter: u64 = 0;
5
6 var lines = std.mem.splitScalar(u8, input, '\n');
7
8 while (lines.next()) |l| {
9 if (l.len == 0) return counter;
10
11 var buff_line: [100]u8 = undefined;
12 parseLine(&buff_line, l);
13 counter += calcJolts(2, &buff_line);
14 }
15
16 return counter;
17}
18
19pub fn pt2(input: []const u8) u64 {
20 var counter: u64 = 0;
21
22 var lines = std.mem.splitScalar(u8, input, '\n');
23
24 while (lines.next()) |l| {
25 if (l.len == 0) return counter;
26
27 var buff_line: [100]u8 = undefined;
28 parseLine(&buff_line, l);
29 counter += calcJolts(12, &buff_line);
30 }
31
32 return counter;
33}
34
35fn parseLine(buff_line: []u8, line: []const u8) void {
36 for (0..line.len, line) |i, l| {
37 const d = l - '0';
38 buff_line[i] = d;
39 }
40}
41
42fn calcJolts(n: usize, js: []const u8) u64 {
43 var counter: u64 = 0;
44 var index: usize = 0;
45 for (0..n) |p| {
46 var inner_index = index;
47
48 // plus one to fix disparity between index (starts at 0) and size
49 const upper_bound = js.len - (n - p) + 1;
50 for (index..upper_bound) |i| {
51 if (js[inner_index] < js[i]) inner_index = i;
52 }
53
54 // the amounts of zeros is inverse to the position of p in relation to
55 // size. At p=0 we have the maximum numbers of zero n. At p=n-1, which
56 // p reached its maximum value, pow(10,0) which is 1 (thanks math for
57 // helping with the edge case).
58 const res = js[inner_index] * std.math.pow(u64, 10, n - p - 1);
59
60 counter += res;
61 index = inner_index + 1; // don't forget to advance index.
62 }
63
64 return counter;
65}
66
67test "Day 3 par 1" {
68 const res = pt1(@embedFile("./input/day3"));
69 try std.testing.expect(res == 17311);
70}
71
72test "Day 3 par 2" {
73 const res = pt2(@embedFile("./input/day3"));
74 try std.testing.expect(res == 171419245422055);
75}