diff --git a/2021/6.zig b/2021/6.zig index c7e2042..dc89505 100644 --- a/2021/6.zig +++ b/2021/6.zig @@ -1,7 +1,14 @@ const std = @import("std"); +const common = @import("./common.zig"); // TODO: solution to day 6 pub fn main() !void { + var fileContents = try common.readFileContents("/home/daniel/.home/.cache/aoc2021/6.input"); const stdout = std.io.getStdOut().writer(); - try stdout.print("Hello, {s}!\n", .{"world"}); + try stdout.print("{s}", .{fileContents}); +} + +/// Calculate lanternFish value +fn lanternFish() i32 { + return 48; } diff --git a/2021/common.zig b/2021/common.zig new file mode 100644 index 0000000..abefa6d --- /dev/null +++ b/2021/common.zig @@ -0,0 +1,18 @@ +const std = @import("std"); + +pub fn readFileContents(file_path: []const u8, alloc: *std.mem.Allocator) anyerror![]u8 { + var gp = std.heap.GeneralPurposeAllocator(.{.safety = true}){}; + defer _ = gp.deinit(); + const alloc = &gp.allocator; + + var path_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; + const path = try std.fs.realpath(file_path, &path_buffer); + + const file = try std.fs.openFileAbsolute(path, .{ .read = true }); + defer file.close(); + + const fb = try file.readToEndAlloc(alloc, 50000); + defer alloc.free(fb); + + return fb; +} diff --git a/2021/seven.nim b/2021/seven.nim new file mode 100644 index 0000000..dce1e78 --- /dev/null +++ b/2021/seven.nim @@ -0,0 +1,20 @@ +import std/[strutils, sequtils, tables, strformat] +import ./common + +proc crabsDistance(input: string): int = + result = int.high() + var max_try = 0 + let dists = input.split(',').map(parseInt) + for d in dists: + if d > max_try: max_try = d + for t in 0..max_try: + let fuel = dists.foldl(a + abs(b - t), 0) + if fuel < result: result = fuel + +let input = 7.loadInputText() +time("day 7 part 1"): echo input.crabsDistance() +# time("day 7 part 2"): echo "?" + +when not defined(release): + let testInput = "16,1,2,0,4,2,7,1,2,14" + doAssert testInput.crabsDistance() == 37