advent-of-code/2024/day1.zig

50 lines
1.4 KiB
Zig
Raw Normal View History

2024-12-02 14:02:31 -05:00
const std = @import("std");
const print = std.debug.print;
pub fn main() !void {
const file = try std.fs.cwd().openFile("day1.txt", .{});
defer file.close();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(gpa.deinit() == .ok);
const allocator = gpa.allocator();
const stat = try file.stat();
const input = try file.reader().readAllAlloc(allocator, stat.size);
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});
}