~charles/misc

2daf5d70852154ae0c3060c7a7c4ef12b89a3744 — Charles A. Daniels 1 year, 6 months ago 78608aa
advent 2022: day 1 part 2 complete
1 files changed, 7 insertions(+), 13 deletions(-)

M advent2022/01/part2.scm
M advent2022/01/part2.scm => advent2022/01/part2.scm +7 -13
@@ 1,25 1,19 @@
#!/usr/bin/csi -script

(import (chicken io))
(import (chicken io) srfi-1)

(define (max a b) (if (> a b) a b))
(define (min a b) (if (< a b) a b))

(define (list-max l) (max (list-max (car l)) (cdr l)))
(define (list-min l) (min (list-min (car l)) (cdr l)))
(define (list-min l) (fold min (car l) (cdr l)))

(define (list-sum l) (
  (if (> (length l) 1)
    (+ (car l) (list-sum (cdr l)))
    (if (= (length l) 1) l 0)
  )
))
(define (list-sum l) (fold-right + 0 l))

;; Replaces the first instance of the value v with the replacement r within
;; the list l, evaluating to a new list with the replacement applied.
(define (replace-first-instance l v r)
  (if (= (car l) v)
    (cons v (cdr l))
    (cons r (cdr l))
    (cons (car l) (replace-first-instance (cdr l) v r))
  )
)


@@ 29,7 23,7 @@
;; if it is larger than the smallest element
(define (n-list-max-merge n l x)
  (if (< (length l) 3)
    (cons l x)
    (cons  x l)
    (let ((least (list-min l)))
      (if (< least x)
        (replace-first-instance l least x)


@@ 50,11 44,11 @@
    (if (eof-object? line)
      l
      (if (= (string-length line) 0)
        (n-list-max-merge n l running)
        (find-most-calories n 0 (n-list-max-merge n l running))
        (find-most-calories n (+ (string->number line) running) l)
      )
    )
  )
)

(print (list-sum (find-most-calories 3 0 '(0))))
(print (list-sum (find-most-calories 3 0 '())))