From 9035d0a8d4d92308d2d2947f756792f85f0cd03c Mon Sep 17 00:00:00 2001 From: xeals Date: Sat, 9 Dec 2023 20:27:00 +1100 Subject: [PATCH] day09 part1 --- src/day09.zig | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/day09.zig diff --git a/src/day09.zig b/src/day09.zig new file mode 100644 index 0000000..df0c347 --- /dev/null +++ b/src/day09.zig @@ -0,0 +1,73 @@ +const std = @import("std"); +const util = @import("util.zig"); +const mem = std.mem; + +pub fn main() !void { + const input = @embedFile("data/day09.txt"); + const sln = try solve(util.gpa, input); + std.debug.print("{d}\n", .{sln.a}); + std.debug.print("{d}\n", .{sln.b}); +} + +const Solution = struct { + a: isize, + b: isize, +}; + +fn drv(alloc: mem.Allocator, seq: []const isize) ![]const isize { + var list = try std.ArrayList(isize).initCapacity(alloc, seq.len - 1); + for (0..seq.len - 1) |i| { + try list.append(seq[i + 1] - seq[i]); + } + return list.toOwnedSlice(); +} + +fn zeroed(seq: []const isize) bool { + for (seq) |n| { + if (n != 0) return false; + } + return true; +} + +fn solve(alloc: mem.Allocator, input: []const u8) !Solution { + var it = util.splitLines(input); + var sum: isize = 0; + while (it.next()) |line| { + if (line.len == 0) continue; + var seqs = std.ArrayList([]const isize).init(alloc); + defer seqs.deinit(); + // Find zero derivation + try seqs.append(try util.parseIntsScalar(isize, alloc, line, .{})); + while (!zeroed(seqs.items[seqs.items.len - 1])) { + try seqs.append(try drv(alloc, seqs.items[seqs.items.len - 1])); + } + // Solve next sequence + var predicted: isize = 0; + for (seqs.items) |seq| { + predicted += seq[seq.len - 1]; + // Clean up + alloc.free(seq); + } + sum += predicted; + } + + return .{ .a = sum, .b = 0 }; +} + +test "silver" { + const input = + \\0 3 6 9 12 15 + \\1 3 6 10 15 21 + \\10 13 16 21 30 45 + ; + const sln = try solve(std.testing.allocator, input); + try std.testing.expectEqual(@as(isize, 114), sln.a); +} + +test "gold" { + const input = + \\ + ; + const sln = try solve(std.testing.allocator, input); + try std.testing.expectEqual(@as(isize, 0), sln.b); +}