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


      1const std = @import("std");
      2const aoc = @import("aoc");
      3
      4fn transform(subject_num: u64, loops: u64) u64 {
      5    var num: u64 = 1;
      6    var i: u64 = 0;
      7    while (i < loops) : (i += 1) {
      8        num *= subject_num;
      9        num %= 20201227;
     10    }
     11    return num;
     12}
     13
     14fn bfLoops(subject_num: u64, pubkey: u64) ?u64 {
     15    var i: u64 = 0;
     16    var tmp: u64 = 1;
     17    while (i < ~@as(u64, 0)) : (i += 1) {
     18        if (tmp == pubkey) return i;
     19        tmp *= subject_num;
     20        tmp %= 20201227;
     21    }
     22    return null;
     23}
     24
     25fn parseInput(door_pubkey: *u64, card_pubkey: *u64, input: []const u8) !void {
     26    var lineit = std.mem.tokenize(u8, input, "\n");
     27    door_pubkey.* = try std.fmt.parseInt(u64, try aoc.unwrap(lineit.next()), 10);
     28    card_pubkey.* = try std.fmt.parseInt(u64, try aoc.unwrap(lineit.next()), 10);
     29}
     30
     31fn part1(allocator: std.mem.Allocator, input: []u8, args: [][]u8) !?[]u8 {
     32    var door_pubkey: u64 = undefined;
     33    var card_pubkey: u64 = undefined;
     34
     35    try parseInput(&door_pubkey, &card_pubkey, input);
     36
     37    if (args.len == 0 or std.mem.eql(u8, args[0], "bf_door")) {
     38        if (bfLoops(7, door_pubkey)) |door_loops| {
     39            std.debug.print("{}\n", .{transform(card_pubkey, door_loops)});
     40            return null;
     41        }
     42    } else if (args.len > 0 and std.mem.eql(u8, args[0], "bf_card")) {
     43        if (bfLoops(7, card_pubkey)) |card_loops| {
     44            const answer = transform(door_pubkey, card_loops);
     45            return try std.fmt.allocPrint(allocator, "{}", .{answer});
     46        }
     47    }
     48    return null;
     49}
     50
     51fn part2(allocator: std.mem.Allocator, input: []u8, args: [][]u8) !?[]u8 {
     52    _ = input;
     53    _ = args;
     54
     55    return try std.fmt.allocPrint(allocator, "", .{});
     56}
     57
     58pub const main = aoc.main(part1, part2, .{ "15217943", "" });