summaryrefslogtreecommitdiff
path: root/src/day01.zig
blob: 2010816c489af2eb2b4bbb3459782e570ddf1df2 (plain)
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
const std = @import("std");
const print = std.debug.print;

pub fn solve(part: []u8, reader: *std.Io.Reader, _: std.mem.Allocator) !void {
    if (std.mem.eql(u8, part, "1")) {
        try part1(reader);
    } else {
        try part2(reader);
    }
}

fn part1(reader: *std.Io.Reader) !void {
    var pos: i32 = 50;
    var zero: usize = 0;
    while (reader.takeDelimiterInclusive('\n')) |line| {
        if (line.len == 0){
            break;
        }

        const numSlice = std.mem.trimRight(u8, line[1..], &[_]u8{'\n'});
        const rotations = try std.fmt.parseInt(i32, numSlice, 10);
        if (line[0] == 'R') {
            pos += rotations;
        } else if (line[0] == 'L'){
            pos -= rotations;
        }

        pos = @mod(pos, 100);

        if (pos == 0) {
            zero += 1;
        }

    } else |_| {
    }

    print("{d}\n", .{zero});
}

fn part2(reader: *std.Io.Reader) !void {
    var pos: i32 = 50;
    var zero: i32 = 0;
    while (reader.takeDelimiterInclusive('\n')) |line| {
        if (line.len == 0){
            break;
        }

        const numSlice = std.mem.trimRight(u8, line[1..], &[_]u8{'\n'});
        var rotations = try std.fmt.parseInt(i32, numSlice, 10);

        zero += @divFloor(rotations, 100);
        rotations = @rem(rotations, 100);
        
        if (line[0] == 'L'){
            rotations *= -1;
        }

        const with_rotations: i32 = pos + rotations;
        const new: i32 = @mod(with_rotations, 100);


        if ((new != with_rotations and pos != 0) or new == 0){
            zero += 1;
        }

        pos = new;


    } else |_| {}

    print("{d}\n", .{zero});
}