diff options
author | Martin Ashby <martin@ashbysoft.com> | 2023-12-10 21:04:30 +0000 |
---|---|---|
committer | Martin Ashby <martin@ashbysoft.com> | 2023-12-10 21:04:30 +0000 |
commit | 328fbedc757756f1e8c8d4a45d3c3e391e77875c (patch) | |
tree | 6ceed3fdbdedc9c2cae233391ef8d3b2eca35fce | |
parent | 4d2632cd6ee460d0f1a5cc2bd8b0ec71d5a24ff8 (diff) | |
download | aoc2023-328fbedc757756f1e8c8d4a45d3c3e391e77875c.tar.gz aoc2023-328fbedc757756f1e8c8d4a45d3c3e391e77875c.tar.bz2 aoc2023-328fbedc757756f1e8c8d4a45d3c3e391e77875c.tar.xz aoc2023-328fbedc757756f1e8c8d4a45d3c3e391e77875c.zip |
Day 9 pt2
-rw-r--r-- | day9.zig | 31 |
1 files changed, 31 insertions, 0 deletions
@@ -2,6 +2,7 @@ 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)}); + try std.fmt.format(std.io.getStdOut().writer(), "day 9 pt2: {}\n", .{try solve_pt2(std.heap.page_allocator, puzzle_input)}); } fn solve_pt1(a: std.mem.Allocator, input: []const u8) !i64 { @@ -44,6 +45,36 @@ test "pt1" { try std.testing.expectEqual(@as(i64, 114), try solve_pt1(std.testing.allocator, test_input)); } +fn solve_pt2(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 prv = nums.items[0] - try predictPrev(a, nums); + // std.log.warn("prv {}", .{prv}); + sum += prv; + } + return sum; +} + +// note uses recursion! +fn predictPrev(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]); + } + return sublist.items[0] - try predictPrev(a, sublist); +} + +test "pt2" { + try std.testing.expectEqual(@as(i64, 2), try solve_pt2(std.testing.allocator, test_input)); +} + const test_input = \\0 3 6 9 12 15 \\1 3 6 10 15 21 |