You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.1 KiB
Zig

const std = @import("std");
pub fn main() !void {
const content = @embedFile("data.txt");
var lines = std.mem.split(u8, content, "\n");
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
var list = std.ArrayList(std.ArrayList(i32)).init(allocator);
defer list.deinit();
while (lines.next()) |line| {
if (line.len == 0) {
break;
}
var history = std.ArrayList(i32).init(allocator);
var nums = std.mem.split(u8, line, " ");
while (nums.next()) |num| {
const parsed = try std.fmt.parseInt(i32, num, 10);
try history.append(parsed);
}
try list.append(history);
}
var part1: i32 = 0;
var part2: i32 = 0;
for (list.items) |history| {
var derived = std.ArrayList(std.ArrayList(i32)).init(allocator);
try derived.append(history);
var cur = history;
while (true) {
var d = try derive(cur, allocator);
try derived.append(d);
cur = d;
var allZero = true;
for (d.items) |item| {
if (item != 0) {
allZero = false;
}
}
if (allZero) {
break;
}
}
var newItem: i32 = 0;
var newItem2: i32 = 0;
for (derived.items, 0..) |_, j| {
// part 1
const idx = derived.items.len - j - 1;
const lastItem = derived.items[idx].getLast();
newItem = lastItem + newItem;
// part 2
const firstItem = derived.items[idx].items[0];
newItem2 = firstItem - newItem2;
}
part1 += newItem;
part2 += newItem2;
}
std.debug.print("Part 1: {d}\n", .{part1});
std.debug.print("Part 2: {d}\n", .{part2});
}
fn derive(history: std.ArrayList(i32), allocator: std.mem.Allocator) !std.ArrayList(i32) {
var list = std.ArrayList(i32).init(allocator);
for (0..history.items.len - 1) |idx| {
try list.append(history.items[idx + 1] - history.items[idx]);
}
return list;
}