~cricket/advent2020

advent2020/07/main.zig -rw-r--r-- 2.0 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
59
60
const std = @import("std");
const input = @embedFile("input");
const mem = std.mem;
const fmt = std.fmt;
const print = std.debug.print;

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

const Bag = struct { color: []const u8, count: usize };
var map = std.StringHashMap([]Bag).init(a);

fn has(name: []const u8) bool {
    var contains = map.get(name) orelse return false; // ?
    for(contains) |contained| {
        if (std.mem.eql(u8, contained.color, "shiny gold bag")) return true;
        if (has(contained.color)) return true;
    }
    return false;
}

fn bags_in(name: []const u8) usize {
    var rb: usize = 0;
    var contains = map.get(name) orelse return 0;
    for(contains) |contained| {
        rb += contained.count + ((bags_in(contained.color)) * contained.count);
    }
    return rb;
}

pub fn main() !void {
    var list = mem.split(input, "\n");
    while (list.next()) |str| {
        var contain_split = mem.split(str, " contain ");
        var bag_name = contain_split.next().?;
        bag_name = bag_name[0..bag_name.len-1];
        var contains = contain_split.next().?;
        var containers = mem.split(contains, ", ");
        var array_list = std.ArrayList(Bag).init(a);
        while (containers.next()) |temp| {
            var contained = temp;
            if (mem.eql(u8, contained, "no other bags.")) break;
            var num = try fmt.parseInt(usize, contained[0..1], 0);
            var bag = contained[0..contained.len-@boolToInt(contained[contained.len-1] == '.')];
            bag = bag[0..bag.len-@boolToInt(bag[bag.len-1] == 's')];
            bag = bag[2..bag.len];
            try array_list.append(Bag{ .color = bag, .count = num });
        }
        try map.put(bag_name, array_list.items);
    }

    var map_it = map.iterator();
    var num: usize = 0;
    var bagsingold: usize = 0;
    while (map_it.next()) |it| {
        num += @boolToInt(has(it.key));
        if(std.mem.eql(u8, it.key, "shiny gold bag")) bagsingold = bags_in(it.key);
    }
    print("{}\n{}\n", .{num, bagsingold});
}