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_3.jl (1968B)


      1 #!/usr/bin/env julia
      2 # https://adventofcode.com/2022/day/3
      3 using AdventOfCode
      4 
      5 example = split("""
      6     vJrwpWtwJgWrhcsFMMfFFhFp
      7     jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
      8     PmmdzqPrVvPwwTWBwg
      9     wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
     10     ttgJtRGJQctTZtZT
     11     CrZsJsPPZsGzwwsLwLmpwMDw""",
     12                 "\n")
     13 input = readlines("data/day_3.txt")
     14 
     15 # Return a tuple of arrays for a rucksack, consisting of the priority values of
     16 # all of the (unique) items in the compartment. This abuses ASCII/UTF-8
     17 # encoding of [a-zA-Z]
     18 function get_compartments(rucksack::String)
     19     rucksack = Vector{UInt8}(rucksack)
     20     rucksack = map(x->(x>Int('Z')) ? x-Int('a')+1 : x-Int('A')+27,
     21                    rucksack)
     22     (rucksack[1:end÷2],
     23      rucksack[end÷2+1:end])
     24 end
     25 
     26 # This is written to assume there's only one item in both compartments
     27 function get_compartment_intersection_priority(rucksack::String)
     28     compartments = get_compartments(rucksack)
     29     intersect(compartments...)[1]
     30 end
     31 
     32 function part_1(input::Array{String,1})
     33     sum(map(get_compartment_intersection_priority, input))
     34 end
     35 @assert part_1(example) == 157
     36 @info part_1(input)
     37 
     38 # For part 2, we don't need to worry about rucksack compartments at all, but I
     39 # already wrote the logic to turn items into values, and reusing
     40 # get_compartments gave me the opportunity to learn about Julia's splat
     41 # operator `...`.
     42 
     43 # This function takes a group of rucksacks (in string format) and finds the
     44 # value of the "badge". Also, you can splat the input to intersect (and I did
     45 # that for my original solution), but I saw somebody else call reduce and that
     46 # feels worth cribbing (even if it's no more efficient).
     47 function get_rucksacks_badge(rucksacks::Array{String,1})
     48     reduce(intersect,
     49            map(x->union(get_compartments(x)...),rucksacks))[1]
     50 end
     51 
     52 function part_2(input::Array{String,1})
     53     sum(map(get_rucksacks_badge,
     54             Iterators.partition(input, 3)))
     55 end
     56 @assert part_2(example) == 70
     57 @info part_2(input)