~cricket/advent2020

advent2020/10/main.zig -rw-r--r-- 1.5 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
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 list = std.ArrayList(usize).init(a);
var items: []usize = undefined;

fn maxKey(map: std.AutoHashMap(usize, usize)) usize {
    var res: usize = 0;
    var map_it = map.iterator();
    while (map_it.next()) |v| {
        if (v.key > res) res = v.key;
    }
    return res;
}

fn part1() usize {
    var diff1: usize = 1;
    var diff3: usize = 1;
    for (items) |v, k| {
        if (k == 0) continue;
        diff1 += @boolToInt(items[k - 1] + 1 == v);
        diff3 += @boolToInt(items[k - 1] + 3 == v);
    }
    return diff1 * diff3;
}

fn part2() usize {
    var ways = std.AutoHashMap(usize, usize).init(a);
    ways.put(0, 1) catch unreachable;
    for (items) |v| {
        const x = if (v < 1) 0 else ways.get(v - 1) orelse 0;
        const y = if (v < 2) 0 else ways.get(v - 2) orelse 0;
        const z = if (v < 3) 0 else ways.get(v - 3) orelse 0;
        ways.put(v, (x + y + z)) catch unreachable;
    }
    return ways.get(maxKey(ways)).?;
}

pub fn main() !void {
    var split = mem.split(input, "\n");
    while (split.next()) |str| {
        const num = try fmt.parseInt(usize, str, 0);
        try list.append(num);
    }
    items = list.items;
    sort.sort(usize, items, {}, comptime sort.asc(usize));

    print("part 1: {}\n", .{part1()});
    print("part 2: {}\n", .{part2()});
}