Paste: AoC 2022 day 20

Author: xr
Mode: factor
Date: Thu, 22 Dec 2022 21:56:40
Plain Text |
! Copyright (C) 2022 Your name.
! See http://factorcode.org/license.txt for BSD license.
USING: math.vectors math.functions aoc vectors math math.parser kernel sequences sequences.extras ;
IN: aoc.2022.20

: remove-nth!* ( from seq -- n )
  [ nth ] [ remove-nth! drop ] 2bi ;

: move-to! ( from to seq -- )
  [ nip remove-nth!* first ] [ nipd insert-nth! ]  3bi ;

! Quotient and remainder based on floor.
: knuthq ( a n -- q ) / floor ;
: knuthr ( a n -- q ) 2dup knuthq * - ;

: calc-index ( a n -- i ) [ [ knuthq ] [ knuthr ] 2bi + ] keep knuthr ;

: shuffle-rule! ( i seq -- )
  [ nth first ]
  [ [ + ] dip length make-index ]
  [ swapd move-to! ] 2tri ;

: action ( i seq -- )
   [ [ sequence? ] find-from drop ] keep
   over
   [ [ shuffle-rule! ] [ action ] 2bi ]
   [ 2drop ]
   if ;

CONSTANT: input P" work/aoc/2022/20/input.txt"
CONSTANT: test-input P" work/aoc/2022/20/test.txt"

: parse ( file -- seq )
  load-file >vector [ dec> 1vector ] map ;

: answer ( seq -- n )
  [ length ]
  [ [ 0 = ] find drop ] bi
  { 1000 2000 3000 } n+v
  [ swap mod ] with map
  swap nths sum ;

: part1 ( file -- seq )
  parse 0 over [ action ] keep
  answer

Annotation: part 1 + part 2

Author: xr
Mode: factor
Date: Fri, 23 Dec 2022 00:35:06
Plain Text |
! Copyright (C) 2022 Your name.
! See http://factorcode.org/license.txt for BSD license.
USING: math.vectors math.functions aoc vectors arrays multiline math math.parser kernel sequences sequences.extras ;
IN: aoc.2022.20

: remove-nth!* ( from seq -- n )
  [ nth ] [ remove-nth! drop ] 2bi ;

: move-to! ( from to seq -- )
  [ nip remove-nth!* ] [ nipd insert-nth! ]  3bi ;

: calc-index ( a n -- i ) -1 + rem ;

: shuffle-rule! ( i seq -- )
  [ nth first ]
  [ [ + ] dip length calc-index ]
  [ swapd move-to! ] 2tri ;

: (action) ( acc seq quot: ( x y -- z ) -- )
   dup [ -rot ] dip 2keep
   pick
   [ [ nip shuffle-rule! ] [ [ nip 1 + ] dip rot (action) ] 3bi ]
   [ 4drop ]
   if ; inline recursive

: seq-find ( i seq -- j )
  [ = ] with [ second ] prepose find drop ;

: action ( i seq -- )
  [ seq-find ] (action) ;

CONSTANT: input P" work/aoc/2022/20/input.txt"
CONSTANT: test-input P" work/aoc/2022/20/test.txt"

: 2vector ( x y -- vec )
  2array >vector ;

: parse ( file -- seq )
  load-file >vector [ [ dec> ] dip 2vector ] map-index ;

: answer ( seq -- n )
  [ first ] map
  dup
  [ length ]
  [ [ 0 = ] find drop ] bi
  { 1000 2000 3000 } n+v
  [ swap mod ] with map
  swap nths sum ;

: parse2 ( file -- seq )
  load-file >vector [ [ dec> 811589153 * ] dip 2vector ] map-index ;

: part ( seq n -- n )
  [ 0 over action ] times
  answer ;

: day20 ( -- )
 input parse 1 part .
 input parse2 10 part . ;

New Annotation

Summary:
Author:
Mode:
Body: