From 31ba31c887ff054de82e83000bf37a847377a62e Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Sat, 10 Dec 2022 14:23:31 +0100 Subject: 2022-10 in zig --- 2022/10-cathode-ray-tube/first.zig | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 2022/10-cathode-ray-tube/first.zig (limited to '2022/10-cathode-ray-tube/first.zig') diff --git a/2022/10-cathode-ray-tube/first.zig b/2022/10-cathode-ray-tube/first.zig new file mode 100644 index 0000000..105903b --- /dev/null +++ b/2022/10-cathode-ray-tube/first.zig @@ -0,0 +1,37 @@ +const std = @import("std"); + +const example = @embedFile("example"); +const input = @embedFile("input"); + +pub fn main() anyerror!void { + try std.testing.expectEqual(solve(example), 13140); + const result = solve(input); + try std.io.getStdOut().writer().print("{}\n", .{result}); +} + +fn solve(puzzle: []const u8) i64 { + var it = std.mem.tokenize(u8, puzzle, "\n"); + var tot: i64 = 0; + var cycle: i64 = 1; + var x: i64 = 1; + var line: []const u8 = undefined; + var prev: ?i64 = null; + // process input + while (cycle <= 220) : (cycle += 1) { + if (@mod(cycle - 20, 40) == 0) { + tot += x * cycle; + } + if (prev) |p| { // cpu is busy adding + x += p; + prev = null; + } else { // read another instruction + line = it.next() orelse break; + if (line[0] == 'a') { + var elts = std.mem.split(u8, line, " "); + _ = elts.next() orelse unreachable; + prev = std.fmt.parseInt(i64, elts.next() orelse unreachable, 10) catch unreachable; + } + } + } + return tot; +} -- cgit v1.2.3