~cricket/advent2020

advent2020/09/main.zig -rw-r--r-- 1.6 KiB
a045fed6cricket day 1-9: rename directories 10 months ago
                                                                                
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
const std = @import("std");
const input = @embedFile("input");
const mem = std.mem;
const fmt = std.fmt;
const sort = std.sort;
const print = std.debug.print;

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const a = &gpa.allocator;
var glist = std.ArrayList(usize).init(a);

fn addsto(x: usize, list: []usize) bool {
    for (list) |v| {
        for (list) |w| {
            if (v + w == x) return true;
        }
    }
    return false;
}

fn subslice(max: usize, list: []usize) []usize {
    var s: usize = 0;
    var k: usize = 1;
    var sum = list[0];
    while (k <= list.len) : (k += 1) {
        const v = list[k];
        while (sum > max and s < k - 1) : (s += 1) sum -= list[s];
        if (sum == max) return list[s .. k - 1];
        if (k < list.len) sum += v;
    }
    return list[0..1];
}

pub fn main() !void {
    var split = mem.split(input, "\n");
    var i: usize = 0;
    while (split.next()) |str| : (i += 1) {
        const val = try fmt.parseInt(usize, str, 0);
        try glist.append(val);

        var list = std.ArrayList(usize).init(a);
        if (i <= 25) continue;
        var k: usize = 0;
        while (k <= 25) : (k += 1) {
            const item = glist.items[i - k];
            try list.append(item);
        }

        if (!addsto(val, list.items)) break;
    }
    const items = glist.items;
    const end = items[i];
    print("part 1: {}\n", .{end});
    const range = subslice(end, items);
    const min = sort.min(usize, range, {}, comptime sort.asc(usize)).?;
    const max = sort.max(usize, range, {}, comptime sort.asc(usize)).?;
    print("part 2: {}\n", .{min + max});
}