const std = @import("std"); const print = std.debug.print; pub fn solve(part: []u8, buffer: []u8, allocator: std.mem.Allocator) !void { var lines = std.mem.splitScalar(u8, buffer, '\n'); var left = std.ArrayList(usize).init(allocator); var right = std.ArrayList(usize).init(allocator); defer left.deinit(); defer right.deinit(); if (std.mem.eql(u8, part, "part1")) { try part1(&lines, &left, &right, allocator); } else { try part2(&lines, &left, &right, allocator); } } fn part1(lines: *std.mem.SplitIterator(u8, .scalar), left: *std.ArrayList(usize), right: *std.ArrayList(usize), allocator: std.mem.Allocator) !void { while (lines.next()) |line| { if (line.len > 0) { var components = std.mem.split(u8, line, " "); try left.append(try std.fmt.parseInt(usize, components.next().?, 10)); try right.append(try std.fmt.parseInt(usize, components.next().?, 10)); } } const left_s = try left.toOwnedSlice(); const right_s = try right.toOwnedSlice(); defer allocator.free(left_s); defer allocator.free(right_s); std.mem.sort(usize, left_s, {}, std.sort.asc(usize)); std.mem.sort(usize, right_s, {}, std.sort.asc(usize)); var sum: usize = 0; for (left_s, right_s) |item_l, item_r| { if (item_l > item_r) { sum += item_l - item_r; } else { sum += item_r - item_l; } } print("Sum is {d}\n", .{sum}); } fn part2(lines: *std.mem.SplitIterator(u8, .scalar), left: *std.ArrayList(usize), right: *std.ArrayList(usize), allocator: std.mem.Allocator) !void { while (lines.next()) |line| { if (line.len > 0) { var components = std.mem.split(u8, line, " "); try left.append(try std.fmt.parseInt(usize, components.next().?, 10)); try right.append(try std.fmt.parseInt(usize, components.next().?, 10)); } } const left_s = try left.toOwnedSlice(); const right_s = try right.toOwnedSlice(); defer allocator.free(left_s); defer allocator.free(right_s); std.mem.sort(usize, right_s, {}, std.sort.asc(usize)); var map = std.AutoHashMap(usize, usize).init(allocator); defer map.deinit(); var sum: usize = 0; for (left_s) |item_l| { sum += map.get(item_l) orelse blk: { var amount: usize = 0; for (right_s) |item_r| { if (item_l == item_r) { amount += item_l; } } try map.put(item_l, amount); break :blk amount; }; } print("Sum is {d}\n", .{sum}); }