Created
September 6, 2023 20:58
-
-
Save mattfreire/6b35da007e6de50f541e0b805297f978 to your computer and use it in GitHub Desktop.
Advent of code day 4
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"); | |
| const ElfRange = struct { low: u8, high: u8 }; | |
| fn parse_u8(s: []const u8) !u8 { | |
| const result = try std.fmt.parseInt(u8, s, 10); | |
| return result; | |
| } | |
| fn parse_range(range: []const u8) !ElfRange { | |
| const sep = std.mem.indexOfScalar(u8, range, '-').?; | |
| const low = try parse_u8(range[0..sep]); | |
| const high = try parse_u8(range[sep + 1 ..]); | |
| return .{ .low = low, .high = high }; | |
| } | |
| fn is_contained(elf1: ElfRange, elf2: ElfRange) bool { | |
| const first_check = elf1.low <= elf2.low and elf1.high >= elf2.high; | |
| const second_check = elf2.low <= elf1.low and elf2.high >= elf1.high; | |
| return first_check or second_check; | |
| } | |
| pub fn main() !void { | |
| const fileName = "day4.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 count: u32 = 0; | |
| var it = std.mem.tokenizeAny(u8, read_buf, "\n"); | |
| while (it.next()) |line| { | |
| // std.debug.print("{s}", .{line}); | |
| const sep = std.mem.indexOfScalar(u8, line, ',').?; | |
| const first_elf = try parse_range(line[0..sep]); | |
| const second_elf = try parse_range(line[sep + 1 ..]); | |
| const contained = is_contained(first_elf, second_elf); | |
| if (contained) count += 1; | |
| std.debug.print("{}:{} is contained: {}\n", .{ first_elf, second_elf, contained }); | |
| } | |
| std.debug.print("total: {}\n", .{count}); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment