From 24669a60f06bde387fd2d16642f7585849dca060 Mon Sep 17 00:00:00 2001 From: xeals Date: Wed, 6 Dec 2023 16:25:34 +1100 Subject: [PATCH] wtf happened in day06 --- src/day06.zig | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 src/day06.zig diff --git a/src/day06.zig b/src/day06.zig new file mode 100644 index 0000000..e874dac --- /dev/null +++ b/src/day06.zig @@ -0,0 +1,85 @@ +const std = @import("std"); +const util = @import("util.zig"); +const mem = std.mem; + +pub fn main() !void { + const input = @embedFile("data/day06.txt"); + const sln = try solve(util.gpa, input); + std.debug.print("{d}\n", .{sln.a}); + std.debug.print("{d}\n", .{sln.b}); +} + +const Solution = struct { + a: usize, + b: usize, +}; + +const Race = struct { + time: usize, + distance: usize, +}; + +fn solve(alloc: mem.Allocator, input: []const u8) !Solution { + const races: []Race = r: { + var it = util.splitLines(input); + const times = try util.parseIntsScalar(usize, alloc, it.next().?[10..], .{}); + const distances = try util.parseIntsScalar(usize, alloc, it.next().?[10..], .{}); + defer alloc.free(times); + defer alloc.free(distances); + var al = try std.ArrayList(Race).initCapacity(alloc, times.len); + for (times, distances) |t, d| { + try al.append(.{ .time = t, .distance = d }); + } + break :r try al.toOwnedSlice(); + }; + defer alloc.free(races); + + const bigRace: Race = r: { + var it = util.splitLines(input); + var vals: [2]usize = undefined; + for (0..vals.len) |i| { + const line = try mem.replaceOwned(u8, alloc, it.next().?[10..], " ", ""); + defer alloc.free(line); + vals[i] = try std.fmt.parseInt(usize, line, 10); + } + break :r .{ .time = vals[0], .distance = vals[1] }; + }; + + var result: usize = 1; + for (races) |race| { + var winning: usize = 0; + for (0..race.time - 1) |speed| { + const distance = speed * (race.time - speed); + if (distance > race.distance) winning += 1; + } + result *= winning; + } + + var result2: usize = 1; + var winning2: usize = 0; + for (0..bigRace.time - 1) |speed| { + const distance = speed * (bigRace.time - speed); + if (distance > bigRace.distance) winning2 += 1; + } + result2 *= winning2; + + return .{ .a = result, .b = result2 }; +} + +test "silver" { + const input = + \\Time: 7 15 30 + \\Distance: 9 40 200 + ; + const sln = try solve(std.testing.allocator, input); + try std.testing.expectEqual(@as(usize, 288), sln.a); +} + +test "gold" { + const input = + \\Time: 7 15 30 + \\Distance: 9 40 200 + ; + const sln = try solve(std.testing.allocator, input); + try std.testing.expectEqual(@as(usize, 288), sln.b); +}