USING: io.encodings.ascii io.files kernel literals math math.matrices math.parser math.statistics prettyprint sequences ; CONSTANT: input $[ "input.txt" ascii file-lines ] : 1|0 ( ? -- n ) CHAR: 1 CHAR: 0 ? ; : part1 ( -- ) input flip [ mode ] map dup [ CHAR: 0 = 1|0 ] map [ bin> ] bi@ * . ; : s ( seq n -- count ) [ = ] curry count ; : counts ( seq -- 1s 0s ) [ CHAR: 1 s ] [ CHAR: 0 s ] bi ; : oxygen ( seq -- n ) counts >= 1|0 ; ! a custom mode : co2 ( seq -- n ) counts < 1|0 ; ! a custom mode ! Filter sequence of binary numbers by bit criteria of the nth ! bit given a mode quotation. : pare ( ... n seq quot: ( ... seq -- ... mode ) -- ... newseq ) [ 2dup col ] dip call swapd '[ _ swap nth _ = ] filter ; inline ! Find the rating given a mode quotation. : rating ( ... seq quot: ( ... seq -- ... mode ) -- ... n ) 0 -rot [ [ dup length 1 > ] ] dip '[ dupd _ pare [ 1 + ] dip ] while nip first bin> ; inline : part2 ( -- ) input [ oxygen ] rating input [ co2 ] rating * . ; part1 part2