07: part1+2 (zig)
This commit is contained in:
parent
c9e026c8f3
commit
19051b6fc9
1 changed files with 49 additions and 0 deletions
49
7/solve.zig
Normal file
49
7/solve.zig
Normal file
|
@ -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});
|
||||||
|
}
|
Loading…
Reference in a new issue