diff options
| author | Mistivia <i@mistivia.com> | 2024-12-03 13:45:32 +0800 |
|---|---|---|
| committer | Mistivia <i@mistivia.com> | 2024-12-03 13:45:32 +0800 |
| commit | 1c64562386506550cae91b01707d66b9bf1c09f0 (patch) | |
| tree | 60b5d47435e87e4d8bfe3d11c8a5c5864b792d43 /03/2.scm | |
| parent | 7f026cafe35eb5dbd79432cafbe0ad6f74386130 (diff) | |
day 3
Diffstat (limited to '03/2.scm')
| -rw-r--r-- | 03/2.scm | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/03/2.scm b/03/2.scm new file mode 100644 index 0000000..96eda29 --- /dev/null +++ b/03/2.scm @@ -0,0 +1,46 @@ +(import (chicken io)) +(import regex) +(import matchable) +(import (chicken string)) + +(define in-str + (with-input-from-file "input" read-string)) + +;; (display in-str) +(define re + "mul\\([0-9]+,[0-9]+\\)|do\\(\\)|don't\\(\\)") + +(define matched + (let loop ((start 0) (result '())) + (define search-ret (string-search re in-str start)) + (if (not search-ret) + (reverse result) + (loop (cadar (string-search-positions re in-str start)) + (cons (car search-ret) result))))) + +(define (extract-numbers str) + (define nums-str (substring str 4 (- (string-length str) 1))) + (map string->number (string-split nums-str ","))) + +(define (process-instr str) + (cond ((string-search "mul" str) (extract-numbers str)) + ((string-search "do\\(" str) 'do) + (else 'dont))) + +(define (calculate str) + (define vals (extract-numbers str)) + (* (car vals) (cadr vals))) + +(define sum + (let loop ((is-do #t) + (lst (map process-instr matched)) + (ret 0)) + (match lst + (() ret) + (('do . r) (loop #t r ret)) + (('dont . r) (loop #f r ret)) + (((a b) . r) (if is-do + (loop is-do r (+ ret (* a b))) + (loop is-do r ret)))))) + +(display sum) |
