view 2022/04/04.jl @ 60:bfee0c4830d2

Day 11 Part 1 + 2
author Lewin Bormann <lbo@spheniscida.de>
date Fri, 22 Dec 2023 21:35:47 +0100
parents 05ddc45b4210
children
line wrap: on
line source

using Transducers
import BenchmarkTools

const input::String = "04/input.txt";

struct Range
    a::Int
    b::Int
end

function torange(s::AbstractString)::Range
    a, b = split(s, '-');
    Range(parse(Int, a), parse(Int, b))
end

function containsfully(a::Range, b::Range)::Bool
    (a.a <= b.a && a.b >= b.b) || (b.a <= a.a && b.b >= a.b)
end

function overlaps(a::Range, b::Range)::Bool
    containsfully(a, b) || (a.a <= b.a && a.b >= b.a && a.b <= b.b) || (a.a >= b.a && a.b >= b.b && a.a <= b.b)
end

function parse_ranges(fh::IO)::Vector{Tuple{Range,Range}}
    collect(eachline(fh) |>
        Map(l -> split(chomp(l), ",")[1:2]) |>
        Map(es -> torange.(es)) |>
        Map(Tuple))
end

function part1(rs::Vector{Tuple{Range,Range}})::Int
    (rs |>
     Map(es -> containsfully(es...)) |>
     sum)
end

function part2(rs::Vector{Tuple{Range,Range}})::Int
    (rs |>
    Map(t -> overlaps(t...)) |>
    sum)
end

function run_04(f::String)::Tuple{Int,Int}
    open(f; read=true) do fh
        rs = parse_ranges(fh);
        a = part1(rs);
        b = part2(rs);
        (a, b)
    end
end

println(run_04(input));