Compare commits
No commits in common. "9b8ae4f350e7ec4824aa29067085caf23f619f32" and "3d36485a5201cacc2bb2612ca142f07b012e2e95" have entirely different histories.
9b8ae4f350
...
3d36485a52
@ -1,84 +0,0 @@
|
||||
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 prev_sum: isize = 0;
|
||||
var next_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]));
|
||||
}
|
||||
// Extrapolate
|
||||
var next: isize = 0;
|
||||
var prev: isize = 0;
|
||||
for (seqs.items) |seq| {
|
||||
next += seq[seq.len - 1];
|
||||
}
|
||||
for (0..seqs.items.len) |i| {
|
||||
prev = seqs.items[seqs.items.len - i - 1][0] - prev;
|
||||
}
|
||||
for (seqs.items) |seq| {
|
||||
// Clean up
|
||||
alloc.free(seq);
|
||||
}
|
||||
prev_sum += prev;
|
||||
next_sum += next;
|
||||
}
|
||||
|
||||
return .{ .a = next_sum, .b = prev_sum };
|
||||
}
|
||||
|
||||
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 =
|
||||
\\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, 2), sln.b);
|
||||
}
|
Loading…
Reference in New Issue
Block a user