This commit is contained in:
2024-12-01 01:48:01 -06:00
commit 551311fca6
4 changed files with 248 additions and 0 deletions

106
01/src/main.zig Normal file
View File

@@ -0,0 +1,106 @@
// Okay! First time using zig!
// The compiler warnings are worse than C's.
// But whatever, I'm starting to get used to some of it?
// I think?
// Still nowhere near idiomatic, sure I'm missing lots of better ways
// But hey! It worked
const std = @import("std");
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const alloc = arena.allocator();
const test_data = @embedFile("test");
const input_data = @embedFile("input");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const value1 = try run1(input_data);
try stdout.print("{d}\n", .{value1});
const value2 = try run2(input_data);
try stdout.print("{d}\n", .{value2});
}
test "test input part 2" {
const value = try run2(test_data);
std.debug.print("{d}\n", .{value});
try std.testing.expectEqual(value, 31);
}
test "test input part 1" {
const value = try run1(test_data);
std.debug.print("{d}\n", .{value});
try std.testing.expectEqual(value, 11);
}
fn run2(s: []const u8) !i64 {
var arrs = [_]std.ArrayList(i64){ std.ArrayList(i64).init(alloc), std.ArrayList(i64).init(alloc) };
var lines = std.mem.splitScalar(u8, s, '\n');
while (lines.next()) |line| {
std.debug.print("{s}\n", .{line});
var split = std.mem.splitScalar(u8, line, ' ');
var c: u8 = 0;
while (split.next()) |i| {
// idk how to put this inside the while
if (c >= 2) break;
if (std.mem.eql(u8, i, "")) continue;
const num = try std.fmt.parseInt(i64, i, 10);
try arrs[c].append(num);
c += 1;
}
}
// this is a lot of recalc, but these lists aren't that long so whatever
// i think it's O(n) so good enough
var sim_score: i64 = 0;
for (arrs[0].items) |x| {
for (arrs[1].items) |y| {
if (x == y) {
sim_score += x;
}
}
}
return sim_score;
}
fn run1(s: []const u8) !u64 {
var arrs = [_]std.ArrayList(i64){ std.ArrayList(i64).init(alloc), std.ArrayList(i64).init(alloc) };
var lines = std.mem.splitScalar(u8, s, '\n');
while (lines.next()) |line| {
std.debug.print("{s}\n", .{line});
var split = std.mem.splitScalar(u8, line, ' ');
var c: u8 = 0;
while (split.next()) |i| {
// idk how to put this inside the while
if (c >= 2) break;
if (std.mem.eql(u8, i, "")) continue;
const num = try std.fmt.parseInt(i64, i, 10);
try arrs[c].append(num);
c += 1;
}
}
for (arrs) |arr| {
std.mem.sort(i64, arr.items, {}, comptime std.sort.asc(i64));
}
for (arrs) |arr| {
for (arr.items) |e| {
std.debug.print("{d} ", .{e});
}
std.debug.print("\n", .{});
}
var total_dist: u64 = 0;
const len = arrs[0].items.len;
for (0..len) |i| {
total_dist += @abs(arrs[0].items[i] - arrs[1].items[i]);
}
return total_dist;
}