aoc-2020-zig

Advent of Code 2020 Solutions in Zig
git clone https://git.sinitax.com/sinitax/aoc-2020-zig
Log | Files | Refs | README | sfeed.txt

main.zig (1975B)


      1const std = @import("std");
      2const aoc = @import("aoc");
      3
      4const Occurance = struct { last: u32, beforelast: u32 };
      5
      6fn getNthSpoken(allocator: std.mem.Allocator, input: []u8, spoken: u32) !u32 {
      7    var occurances = std.AutoHashMap(u32, Occurance).init(allocator);
      8    defer occurances.deinit();
      9
     10    var intlist = std.ArrayList(u32).init(allocator);
     11    defer intlist.deinit();
     12
     13    var numit = std.mem.tokenize(u8, input, "\n,");
     14    var i: u32 = 0;
     15    while (numit.next()) |numstr| : (i += 1) {
     16        const num = try std.fmt.parseInt(u32, numstr, 10);
     17        try intlist.append(num);
     18        try occurances.put(num, Occurance{ .last = i, .beforelast = i });
     19    }
     20
     21    while (i < spoken) : (i += 1) {
     22        if (aoc.debug and i % 100000 == 0)
     23            aoc.debugfmt("\r{}", .{i});
     24
     25        const num = intlist.items[i - 1];
     26        var entry = occurances.getEntry(num);
     27        var diff: u32 = 0;
     28        if (entry) |occ_entry| {
     29            diff = occ_entry.value_ptr.last - occ_entry.value_ptr.beforelast;
     30        }
     31        entry = occurances.getEntry(diff);
     32        if (entry) |occ_entry| {
     33            occ_entry.value_ptr.beforelast = occ_entry.value_ptr.last;
     34            occ_entry.value_ptr.last = i;
     35        } else {
     36            try occurances.put(diff, Occurance{ .last = i, .beforelast = i });
     37        }
     38        try intlist.append(diff);
     39    }
     40
     41    if (aoc.debug)
     42        aoc.debugfmt("\r               \r", .{});
     43
     44    return intlist.items[spoken - 1];
     45}
     46
     47fn part1(allocator: std.mem.Allocator, input: []u8, args: [][]u8) !?[]u8 {
     48    _ = args;
     49
     50    const answer = try getNthSpoken(allocator, input, 2020);
     51
     52    return try std.fmt.allocPrint(allocator, "{}", .{answer});
     53}
     54
     55fn part2(allocator: std.mem.Allocator, input: []u8, args: [][]u8) !?[]u8 {
     56    _ = args;
     57
     58    const answer = try getNthSpoken(allocator, input, 30000000);
     59
     60    return try std.fmt.allocPrint(allocator, "{}", .{answer});
     61}
     62
     63pub const main = aoc.main(part1, part2, .{ "1259", "689" });