advent_of_code_2022

My (attempted) solutions to the 2022 Advent of Code
git clone https://git.eamoncaddigan.net/advent_of_code_2022.git
Log | Files | Refs | README

day_13.jl (1825B)


      1 #!/usr/bin/env julia
      2 # https://adventofcode.com/2022/day/13
      3 using AdventOfCode
      4 
      5 example = readlines(IOBuffer("""
      6     [1,1,3,1,1]
      7     [1,1,5,1,1]
      8 
      9     [[1],[2,3,4]]
     10     [[1],4]
     11 
     12     [9]
     13     [[8,7,6]]
     14 
     15     [[4,4],4,4]
     16     [[4,4],4,4,4]
     17 
     18     [7,7,7,7]
     19     [7,7,7]
     20 
     21     []
     22     [3]
     23 
     24     [[[]]]
     25     [[]]
     26 
     27     [1,[2,[3,[4,[5,6,7]]]],8,9]
     28     [1,[2,[3,[4,[5,6,0]]]],8,9]"""))
     29 input = readlines("data/day_13.txt")
     30 
     31 """
     32 Compare packets using AoC day 13 logic.
     33 """
     34 function comparesides(left::Int, right::Int)
     35     if left < right
     36         "right"
     37     elseif left > right
     38         "wrong"
     39     else
     40         "continue"
     41     end
     42 end
     43 
     44 function comparesides(left::Vector{<:Any}, right::Vector{<:Any})
     45     for i = 1:min(length(left), length(right))
     46         i_result = comparesides(left[i], right[i])
     47         if i_result != "continue"
     48             return i_result
     49         end
     50     end
     51 
     52     if length(left) < length(right)
     53         "right"
     54     elseif length(left) > length(right)
     55         "wrong"
     56     else
     57         "continue"
     58     end
     59 end
     60 
     61 comparesides(left::Int, right::Vector{<:Any}) = comparesides([left], right)
     62 
     63 comparesides(left::Vector{<:Any}, right::Int) = comparesides(left, [right])
     64 
     65 """
     66 Read the input and return a list of packets.
     67 """
     68 function parse_input(input)
     69     map(eval ∘ Meta.parse, filter(!=(""), input))
     70 end
     71 
     72 function part_1(input)
     73     packetorder = map(x->comparesides(x[1], x[2]),
     74                       Iterators.partition(parse_input(input), 2))
     75     (packetorder .== "right") |> findall |> sum
     76 end
     77 @assert part_1(example) == 13
     78 @info part_1(input)
     79 
     80 function part_2(input)
     81     packets = parse_input(input)
     82     append!(packets, [ [[2]], [[6]] ])
     83     sort!(packets, lt = (x, y)->comparesides(x, y) == "right")
     84     findfirst(==([[2]]), packets) * findfirst(==([[6]]), packets)
     85 end
     86 @assert part_2(example) == 140
     87 @info part_2(input)