diff options
author | Martin Ashby <martin@ashbysoft.com> | 2023-12-10 20:58:46 +0000 |
---|---|---|
committer | Martin Ashby <martin@ashbysoft.com> | 2023-12-10 20:58:46 +0000 |
commit | 4d2632cd6ee460d0f1a5cc2bd8b0ec71d5a24ff8 (patch) | |
tree | c437377fa706f49e76c2c142099f4628f5af50ce /day9.zig | |
parent | 18789f1f8684d0f297d0a4b7e88b57a88640642c (diff) | |
download | aoc2023-4d2632cd6ee460d0f1a5cc2bd8b0ec71d5a24ff8.tar.gz aoc2023-4d2632cd6ee460d0f1a5cc2bd8b0ec71d5a24ff8.tar.bz2 aoc2023-4d2632cd6ee460d0f1a5cc2bd8b0ec71d5a24ff8.tar.xz aoc2023-4d2632cd6ee460d0f1a5cc2bd8b0ec71d5a24ff8.zip |
day9 pt1
Diffstat (limited to 'day9.zig')
-rw-r--r-- | day9.zig | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/day9.zig b/day9.zig new file mode 100644 index 0000000..15863af --- /dev/null +++ b/day9.zig @@ -0,0 +1,53 @@ +const std = @import("std"); + +pub fn main() !void { + try std.fmt.format(std.io.getStdOut().writer(), "day 9 pt1: {}\n", .{try solve_pt1(std.heap.page_allocator, puzzle_input)}); +} + +fn solve_pt1(a: std.mem.Allocator, input: []const u8) !i64 { + var sum: i64 = 0; + var spl = std.mem.split(u8, input, "\n"); + while (spl.next()) |line| { + const nums = try readnums(a, line); + defer nums.deinit(); + const nxt = nums.getLast() + try predictNext(a, nums); + // std.log.warn("nxt {}", .{nxt}); + sum += nxt; + } + return sum; +} + +// note uses recursion! +fn predictNext(a: std.mem.Allocator, list: std.ArrayList(i64)) !i64 { + if (std.mem.allEqual(i64, list.items, 0)) { + return 0; + } + var sublist = std.ArrayList(i64).init(a); + defer sublist.deinit(); + for (1..list.items.len) |ix| { + try sublist.append(list.items[ix] - list.items[ix - 1]); + } + const nxt_diff = try predictNext(a, sublist); + return sublist.getLast() + nxt_diff; +} + +fn readnums(a: std.mem.Allocator, input: []const u8) !std.ArrayList(i64) { + var toks = std.mem.tokenize(u8, input, " "); + var res = std.ArrayList(i64).init(a); + while (toks.next()) |tok| { + try res.append(try std.fmt.parseInt(i64, tok, 10)); + } + return res; +} + +test "pt1" { + try std.testing.expectEqual(@as(i64, 114), try solve_pt1(std.testing.allocator, test_input)); +} + +const test_input = + \\0 3 6 9 12 15 + \\1 3 6 10 15 21 + \\10 13 16 21 30 45 +; + +const puzzle_input = @embedFile("day9.in"); |