const std = @import("std");
const INPUT = "14,3,1,0,9,5";
const Str = []const u8;
pub fn first(allocator: ?std.mem.Allocator) anyerror!usize {
return try getLast(allocator.?, INPUT, 2020);
}
pub fn second(allocator: ?std.mem.Allocator) anyerror!usize {
return try getLast(allocator.?, INPUT, 30_000_000);
}
fn getLast(allocator: std.mem.Allocator, input: Str, limit: usize) !usize {
var spoken = std.AutoHashMap(usize, usize).init(allocator);
defer spoken.deinit();
var starting = std.mem.tokenize(u8, input, ",");
var last: usize = undefined;
var round: usize = 1;
while (starting.next()) |st| : (round += 1) {
const num = try std.fmt.parseUnsigned(usize, st, 0);
try spoken.put(num, round);
last = num;
}
// Van Eck Sequence
round -= 1;
while (round < limit) : (round += 1) {
const next = round - (spoken.get(last) orelse round);
try spoken.put(last, round);
last = next;
}
return last;
}
test "day15a" {
try std.testing.expectEqual(@as(usize, 614), try first(std.testing.allocator));
}
test "day15b" {
try std.testing.expectEqual(@as(usize, 1065), try second(std.testing.allocator));
}