Learning Racket. Day 1 and 2 of AOC2021

master
Dustin Swan 3 years ago
commit 81ed00b49a
Signed by: dustinswan
GPG Key ID: AB49BD6B2B3A6377

@ -0,0 +1,48 @@
#lang racket
(define test-data (list
199
200
208
210
200
207
240
269
260
263
))
; part 1
(define (sum data)
(cdr
(foldl (λ (el acc)
(let ([prev (car acc)]
[total (cdr acc)])
(if (> el prev)
(cons el (+ 1 total))
(cons el total))))
(cons (car data) 0)
data)))
(define part1 (sum test-data))
; part 2
; fold over the data
; initial value will be a pair of 2 lists
; first list is the original list, 2nd is the new sliding window
(define sliding-window
(reverse
(cdr
(foldl (λ (el acc)
;(writeln acc) ; debug
(let ([orig (car acc)] ; grab the rest of the original list from the accumulator
[window (cdr acc)] ; grab the window list that we have so far
[one (car (car acc))] ; first element of original list
[two (car (rest (car acc)))]
[three (car (rest (rest (car acc))))])
(cons (rest orig) (cons (+ one two three) window)))) ; return a pair - first elem is the new window list. 2nd elem is the rest of the original list
(cons (append test-data (list 0 0)) empty) ; start with an empty window list an the original list. add 2 0s at the end to cheat
test-data))))
(define part2 (sum sliding-window))

@ -0,0 +1,40 @@
#lang racket
(define file "day2.txt")
(define lines (file->lines file))
(define steps (map string-split lines))
; part 1
(define (modify-position step position)
; (writeln position)
(let ([instruction (car step)]
[magnitude (string->number (second step))]
[forwardness (car position)]
[depth (cdr position)])
(cond [(equal? instruction "forward") (cons (+ forwardness magnitude) depth)]
[(equal? instruction "up") (cons forwardness (- depth magnitude))]
[(equal? instruction "down") (cons forwardness (+ depth magnitude))])))
(define position (foldl modify-position (cons 0 0) steps)) ; (forwardness, depth)
(define part1 (* (car position) (cdr position)))
; part 2
(define (modify-position2 step position)
; (writeln position)
(let ([instruction (first step)]
[magnitude (string->number (second step))]
[forwardness (first position)]
[depth (second position)]
[aim (third position)])
(cond [(equal? instruction "forward") (list (+ forwardness magnitude) (+ depth (* aim magnitude)) aim)]
[(equal? instruction "up") (list forwardness depth (- aim magnitude))]
[(equal? instruction "down") (list forwardness depth (+ aim magnitude))])))
(define position2 (foldl modify-position2 (list 0 0 0) steps)) ; (forwardness, depth, aim)
(define part2 (* (first position2) (second position2)))

@ -0,0 +1,6 @@
forward 5
down 5
forward 8
up 3
down 8
forward 2

1000
day2.txt

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save