summaryrefslogtreecommitdiff
path: root/aoc25/src/day1.zig
blob: 74cb2a4183ca88e41a46d3e10b053da88b1ceff6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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;
}