summaryrefslogtreecommitdiff
path: root/src/day-3/part-2.zig
blob: df78ed19b20f4fd535df558895b63f469dece6b4 (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
const std = @import("std");

//returns index
pub fn largest(line: []const u8, start: usize, end: usize) usize {
    var idx: usize = start;

    for(start..end) |i| {
        if(line[i] > line[idx]){
            idx = i;
        }
    }

    return idx;
} 

pub fn main() !void {
    //var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    //defer gpa.deinit();
    //const alloc = gpa.allocator();
    
    const path = "input.txt";
    const fp = try std.fs.cwd().openFile(path, .{.mode = std.fs.File.OpenMode.read_only});
    defer fp.close();
    var reader = fp.reader();

    var buffer: [256]u8 = undefined;

    var total: u64 = 0;

    const need = 12;
    while(try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
        var lastidx: usize = 0;
        var n: u64 = 0;

        for(1 .. need + 1) |i| {
            lastidx = largest(line, lastidx, line.len - (need - i));
            n += std.math.pow(u64, 10, need - i) * (line[lastidx] - '0');
            lastidx += 1;
        }

        total += n;
    }

    std.debug.print("{d}\n", .{total});
}