1
0

puzzle.jl 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using BenchmarkTools
  2. using DataStructures
  3. inputfile = joinpath(@__DIR__, "input.txt")
  4. stack, instructions = split(read(inputfile, String), "\n\n") .|> x -> split(x, "\n")
  5. parse_input() = begin
  6. queues = DefaultDict(Deque{Char})
  7. stackes = DefaultDict(Stack{Char})
  8. for row in stack
  9. for (i, j) in zip(2:4:length(row), 1:length(2:4:length(row)))
  10. if row[i] == ' '
  11. nothing
  12. elseif row[i] == '1'
  13. break
  14. else
  15. push!(queues[j], row[i])
  16. end
  17. end
  18. end
  19. for (index, queue) in queues
  20. while !isempty(queue)
  21. push!(stackes[index], pop!(queue))
  22. end
  23. end
  24. instr =
  25. (instructions .|> split .|> x -> Base.tryparse.(Int, x)) .|>
  26. x -> x[findall(y -> !isnothing(y), x)]
  27. stackes, instr
  28. end
  29. solve1(stackes, instrs) = begin
  30. stackes = deepcopy(stackes)
  31. instrs = deepcopy(instrs)
  32. for (n, from, to) in instrs
  33. for i = 1:n
  34. push!(stackes[to], pop!(stackes[from]))
  35. end
  36. end
  37. join([first(stackes[i]) for i = 1:length(stackes)])
  38. end
  39. solve2(stackes, instrs) = begin
  40. stackes = deepcopy(stackes)
  41. instrs = deepcopy(instrs)
  42. queue = Deque{Char}()
  43. for (n, from, to) in instrs
  44. [push!(queue, pop!(stackes[from])) for i = 1:n]
  45. [push!(stackes[to], pop!(queue)) for i = 1:n]
  46. end
  47. join([first(stackes[i]) for i = 1:length(stackes)])
  48. end
  49. stackes, instrs = parse_input()
  50. print((solve1(stackes, instrs), solve2(stackes, instrs)))
  51. @btime(solve1(stackes, instrs))
  52. @btime(solve2(stackes, instrs))