From 925abcbe2159c3b0ea13670a62b57912bd3e8994 Mon Sep 17 00:00:00 2001 From: Mathias Magnusson Date: Mon, 1 Dec 2025 14:04:25 +0100 Subject: aoc2025: day 1 --- aoc25/src/day1.zig | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 aoc25/src/day1.zig (limited to 'aoc25/src/day1.zig') diff --git a/aoc25/src/day1.zig b/aoc25/src/day1.zig new file mode 100644 index 0000000..74cb2a4 --- /dev/null +++ b/aoc25/src/day1.zig @@ -0,0 +1,95 @@ +const std = @import("std"); + +const test_input = + \\L68 + \\L30 + \\R48 + \\L5 + \\R60 + \\L55 + \\L1 + \\L99 + \\R14 + \\L82 +; + +test part1 { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + try std.testing.expectEqual(3, try part1(allocator, try parse(allocator, test_input))); +} + +test part2 { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + try std.testing.expectEqual(6, try part2(allocator, try parse(allocator, test_input))); +} + +test "part2 a" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + try std.testing.expectEqual(1, try part2(allocator, try parse(allocator, + \\L50 + ))); +} + + +const Direction = enum { left, right }; + +const Input = []struct { + direction: Direction, + amount: u32, +}; + +pub fn parse(allocator: std.mem.Allocator, input: []const u8) !Input { + var lines = std.mem.splitScalar(u8, input, '\n'); + + var rotations = try std.ArrayList(@typeInfo(Input).pointer.child).initCapacity(allocator, 0); + + while (lines.next()) |line| { + if (line.len == 0) continue; + const direction: Direction = switch (line[0]) { + 'L' => .left, + 'R' => .right, + else => return error.InvalidDirection, + }; + const amount = try std.fmt.parseInt(u32, line[1..], 10); + try rotations.append(allocator, .{ .direction = direction, .amount = amount }); + } + + return rotations.toOwnedSlice(allocator); +} + +pub fn part1(_: std.mem.Allocator, input: Input) !u32 { + var dial: i32 = 50; + var password: u32 = 0; + for (input) |rotation| { + dial += switch (rotation.direction) { + .left => -@as(i32, @intCast(rotation.amount)), + .right => @intCast(rotation.amount), + }; + dial = @mod(dial, 100); + if (dial == 0) password += 1; + } + return password; +} + +pub fn part2(_: std.mem.Allocator, input: Input) !u32 { + var dial: i32 = 50; + var password: u32 = 0; + for (input) |rotation| { + // Smoothbrain solution right here + for (0..rotation.amount) |_| { + dial += switch (rotation.direction) { .left => -1, .right => 1 }; + dial = @mod(dial, 100); + if (dial == 0) password += 1; + } + } + return password; +} -- cgit v1.2.3