Solve day 1

This commit is contained in:
Tyler Hallada 2022-12-01 14:20:25 -05:00
parent 960737ff42
commit 7c4b0f342b
4 changed files with 2334 additions and 7 deletions

2263
input/day01.txt Normal file

File diff suppressed because it is too large Load Diff

14
input/day01_test1.txt Normal file
View File

@ -0,0 +1,14 @@
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

View File

@ -1,17 +1,64 @@
const std = @import("std"); const std = @import("std");
pub fn solve_part1() !u32 { const MAX_BYTES = 2048 * 2048;
return 0;
var gpa = std.heap.GeneralPurposeAllocator(.{ .safety = true }){};
const allocator = gpa.allocator();
pub fn solve_part1(filename: []const u8) !usize {
const input_file = try std.fs.cwd().openFile(filename, .{ .mode = std.fs.File.OpenMode.read_only });
defer input_file.close();
const input = try input_file.readToEndAlloc(allocator, MAX_BYTES);
defer allocator.free(input);
var lines = std.mem.split(u8, input, "\n");
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);
} }
pub fn solve_part2() !u32 { if (calories > largest_calories) {
return 0; largest_calories = calories;
}
}
return largest_calories;
}
pub fn solve_part2(filename: []const u8) !usize {
const input_file = try std.fs.cwd().openFile(filename, .{ .mode = std.fs.File.OpenMode.read_only });
defer input_file.close();
const input = try input_file.readToEndAlloc(allocator, MAX_BYTES);
defer allocator.free(input);
var lines = std.mem.split(u8, input, "\n");
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 = elves.toOwnedSlice();
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];
} }
test "solves part1" { test "solves part1" {
try std.testing.expectEqual(solve_part1(), 0); try std.testing.expectEqual(solve_part1("input/day01_test1.txt"), 24000);
} }
test "solves part2" { test "solves part2" {
try std.testing.expectEqual(solve_part2(), 0); try std.testing.expectEqual(solve_part2("input/day01_test1.txt"), 45000);
} }

View File

@ -7,7 +7,10 @@ pub fn main() !void {
var bw = std.io.bufferedWriter(stdout_file); var bw = std.io.bufferedWriter(stdout_file);
const stdout = bw.writer(); const stdout = bw.writer();
try stdout.print("Day 1\nPart 1: {}\nPart 2: {}\n\n", .{ try day01.solve_part1(), try day01.solve_part2() }); try stdout.print("Day 1\nPart 1: {}\nPart 2: {}\n\n", .{
try day01.solve_part1("input/day01.txt"),
try day01.solve_part2("input/day01.txt"),
});
try bw.flush(); try bw.flush();
} }