advent-of-code/2024/day1.zig

46 lines
1.3 KiB
Zig

const std = @import("std");
const print = std.debug.print;
const util = @import("util.zig");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
const input = try util.readAllInput(1, allocator);
defer allocator.free(input);
var l1 = std.ArrayList(i32).init(allocator);
var l2 = std.ArrayList(i32).init(allocator);
defer l1.deinit();
defer l2.deinit();
var lines = std.mem.tokenizeScalar(u8, input, '\n');
while (lines.next()) |line| {
var split = std.mem.tokenizeScalar(u8, line, ' ');
try l1.append(try std.fmt.parseInt(i32, split.next().?, 10));
try l2.append(try std.fmt.parseInt(i32, split.next().?, 10));
}
// PART 1
std.mem.sort(i32, l1.items, {}, std.sort.asc(i32));
std.mem.sort(i32, l2.items, {}, std.sort.asc(i32));
var distance: u32 = 0;
for (l1.items, l2.items) |item1, item2| {
distance += @abs(item1 - item2);
}
// PART 2
var simScore: i32 = 0;
for (l1.items) |item1| {
var count: i32 = 0;
for (l2.items) |item2| {
if (item1 == item2) count += 1;
}
simScore += item1 * count;
}
print("PART 1 - DISTANCE: {d}\n", .{distance});
print("PART 2 - SIMILARITY: {d}\n", .{simScore});
}