const std = @import("std"); fn StackList(comptime T: type, comptime capacity_type: type, comptime capacity: capacity_type) type { return struct { const Self = @This(); mem: [capacity]T, length: capacity_type, fn add(self: *Self, value: T) void { self.mem[self.length] = value; self.length += 1; } fn has(self: *Self, needle: T) bool { for (0..self.length) |i| { if (self.mem[i] == needle) { return true; } } return false; } fn getMutableSlice(self: *Self) []T { return (&self.mem)[0..self.length]; } fn getSlice(self: *const Self) []const T { return self.mem[0..self.length]; } fn init() Self { return Self{ .mem = undefined, .length = 0, }; } }; } fn addDigit(result: anytype, digit: u8) void { result.* = (result.* * 10) + (digit - '0'); } fn canStartWithGroup(springs: []const u8, group_size: usize) bool { if (springs.len < group_size) { return false; } if (springs.len > group_size and springs[group_size] == '#') { return false; } var i: usize = 0; while (i < group_size) : (i += 1) { if (springs[i] == '.') { return false; } } return true; } fn solveBackward(readings: []i64) i64 { var i: usize = 1; while (i < readings.len) : (i += 1) { var j = readings.len - 1; while (j >= i) : (j -= 1) { readings[j] = readings[j] - readings[j - 1]; } } var result: i64 = 0; var sign: i64 = 1; for (readings) |value| { result += sign * value; sign *= -1; } //std.debug.print("backwards: derivatives: {any}, result: {d}\n", .{ readings, result }); return result; } fn solveForward(readings: []i64) i64 { var i: usize = 1; while (i < readings.len) : (i += 1) { var j: usize = 0; while (j < readings.len - i) : (j += 1) { readings[j] = readings[j + 1] - readings[j]; } } var result: i64 = 0; for (readings) |value| { result += value; } //std.debug.print("forwards: derivatives: {any}, result: {d}\n", .{ readings, result }); return result; } fn solveLine(line: []const u8) i64 { var i: usize = 0; var readings = StackList(i64, usize, 31).init(); while (i < line.len) { var number: i64 = 0; var is_negative = false; if (line[i] == '-') { is_negative = true; i += 1; } while (i < line.len and line[i] != ' ') : (i += 1) { addDigit(&number, line[i]); } if (is_negative) { number = -number; } readings.add(number); i += 1; } return solveBackward(readings.getMutableSlice()); } pub fn main() !void { const stdout = std.io.getStdOut().writer(); const raw_in = std.io.getStdIn(); var buffered_reader = std.io.bufferedReader(raw_in.reader()); var reader = buffered_reader.reader(); var result: i64 = 0; var line_buffer: [1000]u8 = undefined; while (try reader.readUntilDelimiterOrEof(&line_buffer, '\n')) |line| { result += solveLine(line); } try stdout.print("{d}\n", .{result}); }