Sample input:
cat sample_input
[D] [N] [C] [Z] [M] [P] 1 2 3
:
move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2
Parsing the file:
filename = get(ARGS, 1, "sample_input")
input = open(f -> read(f, String), filename) |> f -> split(f, "\n\n")
2-element Vector{SubString{String}}: " [D]\n[N] [C]\n[Z] [M] [P]\n 1 2 3" "move 1 from 2 to 1\nmove 3 from 1 to 3\nmove 2 from 2 to 1\nmove 1 from 1 to 2\n"
Parsing the stacks:
function chunk4(stack)
[i % 4 == 0 ? "" : x for (i, x) in enumerate(stack)] |> s -> filter(!isempty, s) |> s -> Iterators.partition(s, 3) |> s -> join.(s)
end
raw_stacks = input[1] |> i -> split.(i, "\n") |> s -> view(s, 1:length(s) - 1) |> s -> chunk4.(s)
3-element Vector{Vector{String}}: [" ", "[D]"] ["[N]", "[C]"] ["[Z]", "[M]", "[P]"]
max_length = raw_stacks |> s -> map(length, s) |> maximum
raw_stacks = [length(s) < max_length ? append!(s, fill(" ", max_length - length(s))) : s for s = raw_stacks]
stacks = hcat(raw_stacks...) |> s -> eachrow(s) |> s -> filter.(b -> b != " ", s)
3-element Vector{Vector{String}}: ["[N]", "[Z]"] ["[D]", "[C]", "[M]"] ["[P]"]
Parsing the steps:
steps = input[2] |> s -> split.(s, "\n") |> s -> filter(!isempty, s)
4-element Vector{SubString{String}}: "move 1 from 2 to 1" "move 3 from 1 to 3" "move 2 from 2 to 1" "move 1 from 1 to 2"
Iterating over steps:
p1_stacks = deepcopy(stacks)
for step in steps
(_, n, _, origin, _, destination) = split(step, " ")
for _ in 1:parse(Int, n)
x = popfirst!(p1_stacks[parse(Int, origin)])
pushfirst!(p1_stacks[parse(Int, destination)], x)
end
end
println("Part 1: ", first.(p1_stacks) |> join |> s -> replace(s, r"[^A-Z]" => ""))
Part 1: CMZ
Part 2:
p2_stacks = deepcopy(stacks)
for step in steps
(_, n, _, origin, _, destination) = split(step, " ")
x = splice!(p2_stacks[parse(Int, origin)], 1:parse(Int, n))
pushfirst!(p2_stacks[parse(Int, destination)], x...)
end
println("Part 2: ", first.(p2_stacks) |> join |> s -> replace(s, r"[^A-Z]" => ""))
Part 2: MCD