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

commit 16930c5f191badf4725c261a4536b36c2ae1587b
parent 89f1b4cc16176e9af1cd4d636565aeee754a76ae
Author: Eamon Caddigan <eamon.caddigan@gmail.com>
Date:   Sun,  4 Dec 2022 06:47:39 -0800

Solution to day 4 (both parts).

Didn't feel like it was worth splittig into two commits.

Diffstat:
Asrc/day_4.jl | 44++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 44 insertions(+), 0 deletions(-)

diff --git a/src/day_4.jl b/src/day_4.jl @@ -0,0 +1,44 @@ +#!/usr/bin/env julia +# https://adventofcode.com/2022/day/4 +using AdventOfCode + +example = split(""" + 2-4,6-8 + 2-3,4-5 + 5-7,7-9 + 2-8,3-7 + 6-6,4-6 + 2-6,4-8""", + "\n") +input = readlines("data/day_4.txt") + +# Split an input line into an array of arrays +function parse_line(inputline::AbstractString) + map(x->parse.(Int, split(x, "-")), split(inputline, ",")) +end + +# Return true iff one assignment range is entirely contained in another +function check_containment(assignments::Array{Array{Int,1},1}) + (assignments[1][1] >= assignments[2][1] && assignments[1][2] <= assignments[2][2]) || + (assignments[2][1] >= assignments[1][1] && assignments[2][2] <= assignments[1][2]) +end + +function part_1(input::Array{<:AbstractString,1}) + sum(map(check_containment, map(parse_line, input))) +end +@assert part_1(example) == 2 +@info part_1(input) + +# For part 2 I'm simply checking if assignments overlap at all. Not too hard + +# Return true iff the assignments overlap at all +function check_overlap(assignments::Array{Array{Int,1},1}) + assignments[1][1] <= assignments[2][2] && + assignments[1][2] >= assignments[2][1] +end + +function part_2(input::Array{<:AbstractString,1}) + sum(map(check_overlap, map(parse_line, input))) +end +@assert part_2(example) == 4 +@info part_2(input)