const std = @import("std"); const mem = std.mem; const fmt = std.fmt; const CharList = std.ArrayList(u8); const input = @embedFile("input"); const n_crates = 9; fn parseCrates(input_iterator: *mem.SplitIterator(u8), comptime n: u8, allocator: mem.Allocator) []CharList { // Return value var crates = allocator.alloc(CharList, n) catch unreachable; for (crates) |*crate| { crate.* = CharList.init(allocator); } // Make sure it's pointing to the start input_iterator.reset(); while (input_iterator.next()) |line| { // Parse until empty line if (line.len == 0) break; // Keep track of which crate we are in var index: usize = 0; for (line) |char, i| { switch (char) { 'A'...'Z' => crates[index].insert(0, char) catch unreachable, else => index = i / 4, } } } return crates; } fn destroyCrates(crates: []CharList) void { for (crates) |*crate| { crate.*.deinit(); } } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var input_iterator = mem.split(u8, input, "\n"); var crates = parseCrates(&input_iterator, n_crates, allocator); //defer destroyCrates(crates); while (input_iterator.next()) |line| { if (line.len == 0) continue; // Print the state for (crates) |crate, i| { std.debug.print("{d} : {s}\n", .{ i, crate.items }); } // Parsing the line to get action var line_iterator = mem.split(u8, line, " "); // n, src, dst var numbers = [_]u8{undefined} ** 3; var index: usize = 0; while (line_iterator.next()) |word| { // Get a number and asign or go to next word numbers[index] = fmt.parseInt(u8, word, 10) catch continue; if (index == 3) { std.debug.print("Word parsing error, index out of bounds", .{}); unreachable; } index += 1; } // Performing the action var i: usize = 0; const n = numbers[0]; const src = numbers[1] - 1; const dst = numbers[2] - 1; std.debug.print("Move {} from {} to {}\n", .{n, src, dst}); while (i < n) : (i += 1) { crates[dst].append(crates[src].pop()) catch unreachable; } } // Printing the final state for (crates) |crate, i| { std.debug.print("{d} : {s}\n", .{ i, crate.items }); } }