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 (2007B)


      1const std = @import("std");
      2const aoc = @import("aoc");
      3
      4const Parts = struct { a: u32, b: u32 };
      5
      6fn findparts(intlist: *const std.ArrayList(u32), sum: u32) ?Parts {
      7    var start: usize = 0;
      8    const items = intlist.items;
      9    var end: usize = items.len - 1;
     10    while (start != end) {
     11        const csum = items[start] + items[end];
     12        if (csum == sum) {
     13            return Parts{ .a = items[start], .b = items[end] };
     14        } else if (csum > sum) {
     15            end -= 1;
     16        } else {
     17            start += 1;
     18        }
     19    }
     20    return null;
     21}
     22
     23fn parse(allocator: std.mem.Allocator, input: []u8) !std.ArrayList(u32) {
     24    var intlist = std.ArrayList(u32).init(allocator);
     25    errdefer intlist.deinit();
     26
     27    var it = std.mem.tokenize(u8, input, "\n");
     28    while (it.next()) |line| {
     29        try intlist.append(try std.fmt.parseInt(u32, line, 10));
     30    }
     31
     32    return intlist;
     33}
     34
     35fn part1(allocator: std.mem.Allocator, input: []u8, args: [][]u8) !?[]u8 {
     36    _ = args;
     37
     38    const intlist = try parse(allocator, input);
     39    defer intlist.deinit();
     40
     41    std.sort.sort(u32, intlist.items, {}, comptime std.sort.asc(u32));
     42
     43    if (findparts(&intlist, 2020)) |parts| {
     44        return try std.fmt.allocPrint(allocator, "{d}", .{parts.a * parts.b});
     45    }
     46
     47    return null;
     48}
     49
     50fn part2(allocator: std.mem.Allocator, input: []u8, args: [][]u8) !?[]u8 {
     51    _ = args;
     52
     53    const intlist = try parse(allocator, input);
     54    defer intlist.deinit();
     55
     56    std.sort.sort(u32, intlist.items, {}, comptime std.sort.asc(u32));
     57
     58    const target: u16 = 2020;
     59    var third: u32 = 0;
     60    while (third < intlist.items.len) : (third += 1) {
     61        const tmp = intlist.items[third];
     62        intlist.items[third] = target + 1;
     63        if (findparts(&intlist, target - tmp)) |parts| {
     64            return try std.fmt.allocPrint(allocator, "{d}", .{parts.a * parts.b * tmp});
     65        }
     66        intlist.items[third] = tmp;
     67    }
     68
     69    return null;
     70}
     71
     72pub const main = aoc.main(part1, part2, .{ "658899", "155806250" });