Last active
October 26, 2023 15:46
-
-
Save mattfreire/45375aa532a5a76f44201dbc5edb0c80 to your computer and use it in GitHub Desktop.
Advent of code day 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const std = @import("std"); | |
| fn find_common(item: []const u8, allocator: std.mem.Allocator) !u8 { | |
| // std.debug.print("{c}\n", .{item}); | |
| const half_length = item.len / 2; | |
| const first_compartment = item[0..half_length]; | |
| const second_compartment = item[half_length..]; | |
| // std.debug.print("{c}\n", .{first_compartment}); | |
| // std.debug.print("{c}\n", .{second_compartment}); | |
| var map = std.AutoHashMap(u8, void).init(allocator); | |
| defer map.deinit(); | |
| for (first_compartment) |i| { | |
| var v = try map.getOrPut(i); | |
| if (!v.found_existing) { | |
| v.value_ptr.* = {}; | |
| } | |
| } | |
| for (second_compartment) |j| { | |
| if (map.contains(j)) { | |
| return j; | |
| } | |
| } | |
| return undefined; | |
| } | |
| fn get_priority(c: u8) u32 { | |
| return if (c >= 'a') c - 'a' + 1 else c - 'A' + 27; | |
| } | |
| pub fn main() !void { | |
| const fileName = "day3.txt"; | |
| const file = try std.fs.cwd().openFile(fileName, .{}); | |
| defer file.close(); | |
| var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); | |
| defer arena.deinit(); | |
| const allocator = arena.allocator(); | |
| const read_buf = try file.readToEndAlloc(allocator, 1024 * 1024); | |
| defer allocator.free(read_buf); | |
| var sum: u32 = 0; | |
| var it = std.mem.tokenizeAny(u8, read_buf, "\n"); | |
| while (it.next()) |item| { | |
| const common_character = try find_common(item, allocator); | |
| const priority = get_priority(common_character); | |
| sum += priority; | |
| std.debug.print("Found common: {c} with priority: {}\n", .{ common_character, priority }); | |
| } | |
| std.debug.print("Total sum: {}\n", .{sum}); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you're missing this after line 11: