From a684d9b23822f3ea99a956e076dd1d87dc796c4c Mon Sep 17 00:00:00 2001 From: xeals Date: Fri, 15 Dec 2023 17:14:28 +1100 Subject: [PATCH] mild washing --- src/day15.zig | 38 +++++++++++--------------------------- 1 file changed, 11 insertions(+), 27 deletions(-) diff --git a/src/day15.zig b/src/day15.zig index 866ab54..eec2179 100644 --- a/src/day15.zig +++ b/src/day15.zig @@ -17,13 +17,13 @@ const Solution = struct { fn hash(input: []const u8) u32 { var v: u32 = 0; for (input) |c| { - v += c; - v *= 17; - v %= 256; + v = ((v + c) * 17) % 256; } return v; } +const SAHM = std.StringArrayHashMap(u8); + fn solve(alloc: mem.Allocator, input: []const u8) !Solution { const trimmed = mem.trimRight(u8, input, "\n\r"); @@ -34,7 +34,7 @@ fn solve(alloc: mem.Allocator, input: []const u8) !Solution { hash_sum += hash(line); } - var boxes: [256]?std.StringArrayHashMap(u8) = [_]?std.StringArrayHashMap(u8){null} ** 256; + var boxes: [256]?SAHM = [_]?SAHM{null} ** 256; it = util.split(trimmed, ','); while (it.next()) |line| { if (line.len == 0) continue; @@ -42,28 +42,17 @@ fn solve(alloc: mem.Allocator, input: []const u8) !Solution { const label = line[0..op]; const label_hash = hash(label); - // Split init instead of using orelse because references. - if (boxes[label_hash] == null) { - boxes[label_hash] = std.StringArrayHashMap(u8).init(alloc); - } - var box = &(boxes[label_hash] orelse unreachable); + var box = &(boxes[label_hash] orelse init: { + var b = SAHM.init(alloc); + boxes[label_hash] = b; + break :init b; + }); switch (line[op]) { '-' => _ = box.orderedRemove(label), - '=' => { - const focus = try std.fmt.parseInt(u8, line[op + 1 ..], 10); - try box.put(label, focus); - }, + '=' => try box.put(label, try std.fmt.parseInt(u8, line[op + 1 ..], 10)), else => unreachable, } - - // std.debug.print("{s}\n", .{ line }); - // for (boxes, 0..) |bx, n| { - // if (bx) |b| { - // std.debug.print("box {}: {any} = {any}\n", .{ n, b.keys(), b.values() }); - // } - // } - // std.debug.print("---\n", .{}); } var focus: usize = 0; @@ -72,12 +61,7 @@ fn solve(alloc: mem.Allocator, input: []const u8) !Solution { var box_it = box.iterator(); var lens_n: usize = 1; while (box_it.next()) |entry| { - const label = entry.key_ptr.*; - _ = label; - const focal_len = entry.value_ptr.*; - const focus_power = box_n * lens_n * focal_len; - // std.debug.print("{s}: box {} * slot {} * focal length {} = {}\n", .{ label, box_n, lens_n, focal_len, focus_power }); - focus += focus_power; + focus += box_n * lens_n * entry.value_ptr.*; lens_n += 1; } box.deinit();