main.zig (2698B)
1const std = @import("std"); 2const aoc = @import("aoc"); 3const Pos = aoc.Pos; 4const Dir = aoc.Dir; 5 6const Ship = struct { pos: Pos, waypoint: Pos, dir: usize }; 7 8fn part1(allocator: std.mem.Allocator, input: []u8, args: [][]u8) !?[]u8 { 9 _ = args; 10 11 var ship = Ship{ .pos = Pos{ .x = 0, .y = 0 }, .waypoint = Pos{ .x = 0, .y = 0 }, .dir = 0 }; 12 var lineit = std.mem.tokenize(u8, input, "\n"); 13 while (lineit.next()) |line| { 14 const val = try std.fmt.parseInt(u32, line[1..], 10); 15 switch (line[0]) { 16 'N' => ship.pos = ship.pos.add(Dir.North.mult(val)), 17 'S' => ship.pos = ship.pos.add(Dir.South.mult(val)), 18 'E' => ship.pos = ship.pos.add(Dir.East.mult(val)), 19 'W' => ship.pos = ship.pos.add(Dir.West.mult(val)), 20 'L' => ship.dir = Dir.nextCCW(ship.dir, @divExact(val, 90)), 21 'R' => ship.dir = Dir.nextCW(ship.dir, @divExact(val, 90)), 22 'F' => ship.pos = ship.pos.add(Dir.dirs[ship.dir].mult(val)), 23 else => { 24 return aoc.Error.InvalidInput; 25 }, 26 } 27 } 28 29 const answer = std.math.absCast(ship.pos.x) + std.math.absCast(ship.pos.y); 30 31 return try std.fmt.allocPrint(allocator, "{d}", .{answer}); 32} 33 34fn part2(allocator: std.mem.Allocator, input: []u8, args: [][]u8) !?[]u8 { 35 _ = args; 36 37 var ship = Ship{ .pos = Pos{ .x = 0, .y = 0 }, .waypoint = Pos{ .x = 10, .y = 1 }, .dir = 0 }; 38 var lineit = std.mem.tokenize(u8, input, "\n"); 39 while (lineit.next()) |line| { 40 const val = try std.fmt.parseInt(u32, line[1..], 10); 41 switch (line[0]) { 42 'N' => ship.waypoint = ship.waypoint.add(Dir.North.mult(val)), 43 'S' => ship.waypoint = ship.waypoint.add(Dir.South.mult(val)), 44 'E' => ship.waypoint = ship.waypoint.add(Dir.East.mult(val)), 45 'W' => ship.waypoint = ship.waypoint.add(Dir.West.mult(val)), 46 'L' => { 47 var new = Dir.rotCCW(ship.waypoint, @divExact(val, 90)); 48 ship.waypoint = new; 49 }, 50 'R' => { 51 var new = Dir.rotCW(ship.waypoint, @divExact(val, 90)); 52 ship.waypoint = new; 53 }, 54 'F' => ship.pos = ship.pos.add(ship.waypoint.mult(val)), 55 else => { 56 return aoc.Error.InvalidInput; 57 }, 58 } 59 aoc.debugfmt("{s} {} {} {} {}\n", .{ line, ship.waypoint.x, ship.waypoint.y, ship.pos.x, ship.pos.y }); 60 } 61 62 const answer = std.math.absCast(ship.pos.x) + std.math.absCast(ship.pos.y); 63 64 return try std.fmt.allocPrint(allocator, "{d}", .{answer}); 65} 66 67pub const main = aoc.main(part1, part2, .{ "1191", "61053" });