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


      1const std = @import("std");
      2const aoc = @import("aoc");
      3
      4const row_count = 128;
      5const col_count = 8;
      6
      7// Input is coded in a way that we can do an implicit binary search by replacing
      8// identifiers for the lower half with "0" and for the upper half with "1"
      9// See commit <f1b717029cf3262c1fa2760124af258924d668da> for actual binary search
     10
     11fn code2Id(input: []const u8) !u32 {
     12    var value: u32 = 0;
     13    for (input) |c|
     14        value = value * 2 + @boolToInt(c == 'B' or c == 'R');
     15    return value;
     16}
     17
     18fn part1(allocator: std.mem.Allocator, input: []u8, args: [][]u8) !?[]u8 {
     19    _ = args;
     20
     21    var lineit = std.mem.tokenize(u8, input, "\n");
     22    var answer: u32 = 0;
     23    while (lineit.next()) |line| {
     24        const id = try code2Id(line[0..10]);
     25        answer = std.math.max(answer, id);
     26    }
     27
     28    return try std.fmt.allocPrint(allocator, "{d}", .{answer});
     29}
     30
     31fn part2(allocator: std.mem.Allocator, input: []u8, args: [][]u8) !?[]u8 {
     32    _ = args;
     33
     34    var lineit = std.mem.tokenize(u8, input, "\n");
     35    var seats = [_]u1{0} ** (row_count * col_count);
     36    var min: u32 = std.math.inf_u32;
     37    while (lineit.next()) |line| {
     38        const id = try code2Id(line);
     39        min = std.math.min(min, id);
     40        seats[id] = 1;
     41    }
     42
     43    for (seats[min..]) |_, i| {
     44        if (seats[min + i] == 0) {
     45            return try std.fmt.allocPrint(allocator, "{d}", .{min + i});
     46        }
     47    }
     48
     49    return null;
     50}
     51
     52pub const main = aoc.main(part1, part2, .{ "850", "599" });