Day 7 part 1 brute-forced
This commit is contained in:
parent
e9f39ca27a
commit
b9a249df6b
3 changed files with 46 additions and 1 deletions
|
@ -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;
|
||||
}
|
||||
|
|
18
2021/common.zig
Normal file
18
2021/common.zig
Normal file
|
@ -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;
|
||||
}
|
20
2021/seven.nim
Normal file
20
2021/seven.nim
Normal file
|
@ -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
|
Loading…
Reference in a new issue