Skip to content

Instantly share code, notes, and snippets.

@peterhellberg
Last active January 13, 2021 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterhellberg/e72f455cfdfa403950996754467f83a4 to your computer and use it in GitHub Desktop.
Save peterhellberg/e72f455cfdfa403950996754467f83a4 to your computer and use it in GitHub Desktop.
Advent Of Code 2020 - 01
const std = @import("std");
const input = @embedFile("input");
const testing = std.testing;
const expect = testing.expect;
const print = std.debug.print;
pub fn main() anyerror!void {
var nums = try numberList(std.heap.page_allocator);
print("Part1: {}\n", .{try part1(nums)});
print("Part2: {}\n", .{try part2(nums)});
}
pub fn numberList(allocator: *std.mem.Allocator) ![]const u32 {
var list = std.ArrayList(u32).init(allocator);
defer list.deinit();
var it = std.mem.split(input, "\n");
while (it.next()) |num| {
try list.append(std.fmt.parseUnsigned(u32, num, 10) catch continue);
}
return list.toOwnedSlice();
}
pub fn part1(nums: []const u32) !u64 {
for (nums) |x, idx0| {
for (nums[idx0 + 1 ..]) |y, idx1| {
if ((x + y) == 2020) {
return x * y;
}
}
}
return 0;
}
test "part1" {
const array = [_]u32{
1721,
979,
366,
299,
675,
1456,
};
const result = try part1(array[0..]);
expect(result == 514579);
}
pub fn part2(nums: []const u32) !u64 {
for (nums) |x, idx0| {
for (nums[idx0 + 1 ..]) |y, idx1| {
for (nums[std.math.max(idx0, idx1) + 1 ..]) |z, idx2| {
if ((x + y + z) == 2020) {
return x * y * z;
}
}
}
}
return 0;
}
test "part2" {
const array = [_]u32{
1721,
979,
366,
299,
675,
1456,
};
const result = try part2(array[0..]);
expect(result == 241861950);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment