-------------| -- Cleanup --| -------------| drop table if exists input_ranges; drop table if exists fresh; drop table if exists ingredients; -----------| -- Setup --| -----------| create unlogged table input_ranges ( low int8, high int8 ); -- Creating a single multirange sped up the part 1 query by a factor of 10! create unlogged table fresh ( range int8multirange ); create unlogged table ingredients ( id int8 primary key ); -----------------| -- Parse input --| -----------------| -- I don't understand these sed things -- I just want the part before or after the empty line -- Client side commands are terminatd with a newline, so no breaky for me \copy input_ranges (low, high) from program'sed "/^$/Q" input/2025/5.txt' with delimiter '-' -- Insert values as inclusive ranges (postgres normalizes them to be half-open) -- because half-open ranges are objectively cooler. insert into fresh (range) select range_agg(int8range(range.low, range.high, '[]')) from input_ranges as range; -- We don't even need a temporary input table for the these \copy ingredients (id) from program 'sed "1,/^$/d" input/2025/5.txt'; ------------| -- Part 1 --| ------------| select count(ingredient.id) as part_1 from ingredients as ingredient inner join fresh on fresh.range @> ingredient.id; ------------| -- Part 2 --| ------------| -- Even for this one the multirange is useful because it does -- all the range merging for us! with flat (range) as ( select unnest(range) from fresh ) select sum(upper(range) - lower(range)) as part_2 from flat;