advent-of-code-2022/src/day01.zig

54 lines
1.5 KiB
Zig
Raw Normal View History

2022-12-01 18:13:35 +00:00
const std = @import("std");
2022-12-01 19:33:09 +00:00
pub const input = @embedFile("input/day01.txt");
const test_input = @embedFile("input/day01_test1.txt");
2022-12-01 19:20:25 +00:00
var gpa = std.heap.GeneralPurposeAllocator(.{ .safety = true }){};
const allocator = gpa.allocator();
2022-12-01 19:33:09 +00:00
pub fn solve_part1(data: []const u8) !usize {
var lines = std.mem.split(u8, data, "\n");
2022-12-01 19:20:25 +00:00
var largest_calories: usize = 0;
var calories: usize = 0;
while (lines.next()) |line| {
if (std.mem.eql(u8, line, "")) {
calories = 0;
} else {
calories += try std.fmt.parseInt(usize, line, 10);
}
if (calories > largest_calories) {
largest_calories = calories;
}
}
return largest_calories;
2022-12-01 18:13:35 +00:00
}
2022-12-01 19:33:09 +00:00
pub fn solve_part2(data: []const u8) !usize {
var lines = std.mem.split(u8, data, "\n");
2022-12-01 19:20:25 +00:00
var elves = std.ArrayList(usize).init(allocator);
defer elves.deinit();
var calories: usize = 0;
while (lines.next()) |line| {
if (std.mem.eql(u8, line, "")) {
try elves.append(calories);
calories = 0;
} else {
calories += try std.fmt.parseInt(usize, line, 10);
}
}
var elves_slice = try elves.toOwnedSlice();
2022-12-01 19:20:25 +00:00
defer allocator.free(elves_slice);
std.sort.sort(usize, elves_slice, {}, comptime std.sort.desc(usize));
return elves_slice[0] + elves_slice[1] + elves_slice[2];
2022-12-01 18:13:35 +00:00
}
test "solves part1" {
2022-12-01 19:33:09 +00:00
try std.testing.expectEqual(solve_part1(test_input), 24000);
2022-12-01 18:13:35 +00:00
}
test "solves part2" {
2022-12-01 19:33:09 +00:00
try std.testing.expectEqual(solve_part2(test_input), 45000);
2022-12-01 18:13:35 +00:00
}