aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorOrfeas <38209077+0xfea5@users.noreply.github.com>2023-12-09 15:59:07 +0200
committerOrfeas <38209077+0xfea5@users.noreply.github.com>2025-10-28 23:20:45 +0200
commitbaae54102946568cb2209d388739a81b26e37b68 (patch)
tree05045f2146068698ea4ff05d4f70ba61ffbb7ba8
parentday8: use tokenizeAny instead of splitAny (diff)
downloadaoc23-baae54102946568cb2209d388739a81b26e37b68.tar.gz
aoc23-baae54102946568cb2209d388739a81b26e37b68.zip
day9
-rw-r--r--day09/example.txt3
-rw-r--r--day09/solution.zig57
2 files changed, 60 insertions, 0 deletions
diff --git a/day09/example.txt b/day09/example.txt
new file mode 100644
index 0000000..539a763
--- /dev/null
+++ b/day09/example.txt
@@ -0,0 +1,3 @@
10 3 6 9 12 15
21 3 6 10 15 21
310 13 16 21 30 45
diff --git a/day09/solution.zig b/day09/solution.zig
new file mode 100644
index 0000000..e445c19
--- /dev/null
+++ b/day09/solution.zig
@@ -0,0 +1,57 @@
1const std = @import("std");
2const print = std.debug.print;
3const assert = std.debug.assert;
4const ArrayList = std.ArrayList;
5const HashMap = std.HashMap;
6const mem = std.mem;
7
8const fin = mem.trim(u8, @embedFile("./input.txt"), &std.ascii.whitespace);
9var gpa = std.heap.GeneralPurposeAllocator(.{}){};
10const allocator = gpa.allocator();
11
12fn evaluate(list: []const i64) struct { i64, i64 } {
13 if (mem.allEqual(i64, list, 0)) {
14 return .{ 0, 0 };
15 }
16
17 const n = list.len;
18 var derivative = ArrayList(i64).init(allocator);
19 defer derivative.deinit();
20
21 for (list[0 .. n - 1], list[1..n]) |curr, next| {
22 derivative.append(next - curr) catch unreachable;
23 }
24
25 const e = evaluate(derivative.items);
26 return .{ list[n - 1] + e, list[0] - e };
27}
28
29pub fn solve(listNums: ArrayList(ArrayList(i64))) void {
30 var part1: i64 = 0;
31 var part2: i64 = 0;
32
33 for (listNums.items) |list| {
34 const e = evaluate(list.items);
35 part1 += e[0];
36 part2 += e[1];
37 }
38
39 print("{d}\n{d}\n", .{ part1, part2 });
40}
41
42pub fn main() !void {
43 var splitLines = mem.splitScalar(u8, fin, '\n');
44 var listNums = ArrayList(ArrayList(i64)).init(allocator);
45
46 while (splitLines.next()) |line| {
47 var listText = mem.tokenizeScalar(u8, line, ' ');
48
49 var row = ArrayList(i64).init(allocator);
50 while (listText.next()) |n| {
51 try row.append(try std.fmt.parseInt(i64, n, 10));
52 }
53
54 try listNums.append(row);
55 }
56 solve(listNums);
57}