! Copyright (C) 2022 Your name. ! See http://factorcode.org/license.txt for BSD license. USING: aoc splitting math sequences accessors math.parser kernel math.bitwise bit-arrays ; IN: aoc2022-4 TUPLE: range { lo integer } { hi integer } ; C: range : at-or-above-lo ( range range -- ? ) [ lo>> ] bi@ >= ; : at-or-below-hi ( range range -- ? ) [ hi>> ] bi@ <= ; : fully-contained? ( range range -- ? ) [ at-or-above-lo ] [ at-or-below-hi ] 2bi and ; : fully-contained-pair? ( range range -- ? ) [ fully-contained? ] [ swap fully-contained? ] 2bi or ; : infix-split ( string quote -- str str ) '[ _ split1-slice [ @ ] bi@ ] call ; inline : parse-range ( str -- range ) "-" [ dec> ] infix-split ; : parse-range-pairs ( str -- range range ) "," [ parse-range ] infix-split ; : part1 ( -- seq ) "resource:work/aoc2022-4/input.txt" load-file [ parse-range-pairs fully-contained-pair? ] map >bit-array bit-count ; : overlap? ( range range -- ? ) [ [ hi>> ] [ lo>> ] bi* >= ] [ at-or-below-hi ] 2bi and ; : overlapping-pair? ( range range -- ? ) [ overlap? ] [ swap overlap? ] 2bi or ; : part2 ( -- n ) "resource:work/aoc2022-4/input.txt" load-file [ parse-range-pairs overlapping-pair? ] map >bit-array bit-count ;