Paste: AoC 2022 Day 7

Author: Kacarott
Mode: factor
Date: Wed, 7 Dec 2022 09:26:25
Plain Text |
! Copyright (C) 2022 Keldan Chapman.
! See http://factorcode.org/license.txt for BSD license.
USING: kernel AOC prettyprint sequences splitting match
       accessors combinators math math.parser ;
IN: AOC.2022.7

TUPLE: directory name parent children size ;
: <directory> ( name parent -- directory ) V{ } clone 0 \ directory boa ;

MATCH-VARS: ?arg ?size ;

: cd ( dir arg -- dir ) {
        { ".." [ parent>> ] }
        { "/" [ dup parent>> [ nip "/" cd ] when* ] }
        [ [ children>> ] dip [ swap name>> = ] curry find nip ]
    } case ;

: mkdir ( dir arg -- dir ) over <directory> over children>> push ;

: run-command ( directory line -- directory )
    " " split {
        { { "$" "cd" ?arg } [ ?arg cd ] }
        { { "$" "ls" } [ ] }
        { { "dir" ?arg } [ ?arg mkdir ] }
        { { ?size ?arg } [ dup size>> ?size dec> + >>size ] }
    } match-cond ;

! Also updates size of each directory
: sum-large-directories ( dir -- size accum )
    [ [ size>> 0 ] keep children>>
    [ sum-large-directories swapd [ + ] 2bi@ ] each
    over 100001 < [ over + ] when ] keep overd size<< ;

: directory>seq ( dir -- seq ) [ children>> [ directory>seq ] map concat ] keep suffix ;

: parse-input ( input -- directory )
    "\n" split harvest [ "/" f <directory> ] dip
    [ run-command ] each "/" cd ;

: part-1 ( input -- result ) parse-input sum-large-directories nip ;
: part-2 ( input -- result ) parse-input
    [ sum-large-directories drop 40000000 - ]
    [ directory>seq [ size>> ] map ] bi
    swap [ >= ] curry filter infimum ;

MAIN: [ 7 read-day-input [ part-1 . ] [ part-2 . ] bi ]

New Annotation

Summary:
Author:
Mode:
Body: