From b9a249df6b05c1a06cb9c8a8de88f15d9249d382 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Tue, 7 Dec 2021 10:06:34 -0600 Subject: [PATCH] Day 7 part 1 brute-forced --- 2021/6.zig | 9 ++++++++- 2021/common.zig | 18 ++++++++++++++++++ 2021/seven.nim | 20 ++++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 2021/common.zig create mode 100644 2021/seven.nim 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