2024: Day 1 complete

This commit is contained in:
Andrew Scott 2024-12-02 14:02:31 -05:00
parent ebaffe961f
commit 56211245c6
Signed by: a
GPG key ID: 7CD5A5977E4931C1
2 changed files with 1049 additions and 0 deletions

1000
2024/day1.txt Normal file

File diff suppressed because it is too large Load diff

49
2024/day1.zig Normal file
View file

@ -0,0 +1,49 @@
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});
}