master
Raw Download raw file
 1const std = @import("std");
 2const io = std.io;
 3const fmt = std.fmt;
 4
 5const Vector = enum { forward, up, down };
 6
 7// Submarine Commands
 8const Command = struct {
 9    vector: Vector,
10    thrust: u8,
11};
12
13const Coordinate = struct {
14    depth: u16,
15    forward: u16,
16};
17
18pub fn main() !void {
19    const stdin = io.getStdIn().reader();
20    const allocator = std.heap.page_allocator;
21
22    // Read from stdin, line by line
23    // split on " ", parse, and
24    // insert into ArrayList of Commands
25    var buf: [128]u8 = undefined;
26    var course = std.ArrayList(Command).init(allocator);
27    defer course.deinit();
28    while (try stdin.readUntilDelimiterOrEof(&buf, '\n')) |line| {
29        var line_parts = std.mem.split(u8, line, " ");
30        var c = Command{
31            .vector = undefined,
32            .thrust = undefined,
33        };
34        const raw_vector = line_parts.first();
35        if (std.mem.eql(u8, raw_vector, "forward")) {
36            c.vector = Vector.forward;
37        } else if (std.mem.eql(u8, raw_vector, "up")) {
38            c.vector = Vector.up;
39        } else if (std.mem.eql(u8, raw_vector, "down")) {
40            c.vector = Vector.down;
41        }
42        var raw_thrust = line_parts.next().?;
43        c.thrust = fmt.parseUnsigned(u8, raw_thrust, 10) catch |err| {
44            std.debug.print("PARSE ERR: {} {s}\n", .{ err, raw_thrust });
45            continue;
46        };
47
48        try course.append(c);
49        //std.debug.print("{}\n", .{c});
50    }
51    var p = Coordinate{
52        .depth = 0,
53        .forward = 0,
54    };
55    const cmds = course.items;
56    for (cmds) |c| {
57        p = switch (c.vector) {
58            .forward => Coordinate{ .depth = p.depth, .forward = p.forward + c.thrust },
59            .up => Coordinate{ .depth = p.depth - c.thrust, .forward = p.forward },
60            .down => Coordinate{ .depth = p.depth + c.thrust, .forward = p.forward },
61        };
62    }
63    const ans: u32 = @as(u32, p.depth) * p.forward;
64    std.debug.print("{}, {d}\n", .{ p, ans });
65}