1
0

mild washing
Some checks failed
Build and test / test (push) Failing after 2m11s

This commit is contained in:
xeals 2023-12-15 17:14:28 +11:00
parent 992673f784
commit a684d9b238
Signed by: xeals
SSH Key Fingerprint: SHA256:pRv+8swQDA+/LuZ7NHj9m006BbKexlNK62OUA01ZZBc

View File

@ -17,13 +17,13 @@ const Solution = struct {
fn hash(input: []const u8) u32 { fn hash(input: []const u8) u32 {
var v: u32 = 0; var v: u32 = 0;
for (input) |c| { for (input) |c| {
v += c; v = ((v + c) * 17) % 256;
v *= 17;
v %= 256;
} }
return v; return v;
} }
const SAHM = std.StringArrayHashMap(u8);
fn solve(alloc: mem.Allocator, input: []const u8) !Solution { fn solve(alloc: mem.Allocator, input: []const u8) !Solution {
const trimmed = mem.trimRight(u8, input, "\n\r"); 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); 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, ','); it = util.split(trimmed, ',');
while (it.next()) |line| { while (it.next()) |line| {
if (line.len == 0) continue; 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 = line[0..op];
const label_hash = hash(label); const label_hash = hash(label);
// Split init instead of using orelse because references. var box = &(boxes[label_hash] orelse init: {
if (boxes[label_hash] == null) { var b = SAHM.init(alloc);
boxes[label_hash] = std.StringArrayHashMap(u8).init(alloc); boxes[label_hash] = b;
} break :init b;
var box = &(boxes[label_hash] orelse unreachable); });
switch (line[op]) { switch (line[op]) {
'-' => _ = box.orderedRemove(label), '-' => _ = box.orderedRemove(label),
'=' => { '=' => try box.put(label, try std.fmt.parseInt(u8, line[op + 1 ..], 10)),
const focus = try std.fmt.parseInt(u8, line[op + 1 ..], 10);
try box.put(label, focus);
},
else => unreachable, 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; var focus: usize = 0;
@ -72,12 +61,7 @@ fn solve(alloc: mem.Allocator, input: []const u8) !Solution {
var box_it = box.iterator(); var box_it = box.iterator();
var lens_n: usize = 1; var lens_n: usize = 1;
while (box_it.next()) |entry| { while (box_it.next()) |entry| {
const label = entry.key_ptr.*; focus += box_n * lens_n * entry.value_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;
lens_n += 1; lens_n += 1;
} }
box.deinit(); box.deinit();