advent-of-code-2021/7/solve.zig
2021-12-18 16:28:02 +01:00

49 lines
1.3 KiB
Zig

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});
}