From 19051b6fc9dfa203506f99715cdc80d0c848d16f Mon Sep 17 00:00:00 2001 From: ptrcnull Date: Tue, 7 Dec 2021 12:47:08 +0100 Subject: [PATCH] 07: part1+2 (zig) --- 7/solve.zig | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 7/solve.zig diff --git a/7/solve.zig b/7/solve.zig new file mode 100644 index 0000000..3ec2d08 --- /dev/null +++ b/7/solve.zig @@ -0,0 +1,49 @@ +const std = @import("std"); + +pub fn main() !void { + var alloc = std.heap.GeneralPurposeAllocator(.{}){}; + defer std.debug.assert(!alloc.deinit()); + var gpa = &alloc.allocator; + + var crabs = std.ArrayList(i32).init(gpa); + defer crabs.deinit(); + + const stdin = std.io.getStdIn().reader(); + + var topCrab: i32 = 0; + var tmp: [32]u8 = undefined; + while (try stdin.readUntilDelimiterOrEof(&tmp, ',')) |line| { + var newLine = if (line[line.len-1] == '\n') line[0..line.len-1] else line; + const crab = try std.fmt.parseInt(i32, newLine, 10); + try crabs.append(crab); + + if (crab > topCrab) { + topCrab = crab; + } + } + + var bestFuel1: u32 = std.math.maxInt(u32); + var bestFuel2: u32 = std.math.maxInt(u32); + + var i: i32 = 0; + while (i < topCrab): (i += 1) { + var fuel1: u32 = 0; + var fuel2: u32 = 0; + + for (crabs.items) |crab| { + var steps = @intCast(u32, try std.math.absInt(crab - i)); + fuel1 += steps; + fuel2 += @divTrunc(steps * (steps + 1), 2); + } + + if (fuel1 < bestFuel1) { + bestFuel1 = fuel1; + } + if (fuel2 < bestFuel2) { + bestFuel2 = fuel2; + } + } + + std.debug.print("{}\n", .{bestFuel1}); + std.debug.print("{}\n", .{bestFuel2}); +}