aboutsummaryrefslogtreecommitdiff
path: root/2024/day03/main.scm
blob: 1a8505dca5ae699599a754435db7ccbd5721e841 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/guile -s
!#

(add-to-load-path (format #f "~a/2024" (getcwd)))
(add-to-load-path (format #f "~a/.." (dirname (current-filename))))

(use-modules
 (aoc-utils)
 (srfi srfi-1)
 (srfi srfi-9)
 (ice-9 regex))

(define mul-rx (make-regexp "mul\\(([0-9]+),([0-9]+)\\)"))

(define (mul str)
  (let ((match (regexp-exec mul-rx str)))
    (* (string->number (match:substring match 1))
       (string->number (match:substring match 2)))))

(define (not-corrupted-mults memory)
  (map match:substring (list-matches mul-rx memory)))

(define (part1 memory)
  (apply + (map mul (not-corrupted-mults memory))))

(define or-rx (make-regexp "do\\(\\)|don't\\(\\)|mul\\([0-9]+,[0-9]+\\)"))

(define (part2 memory)
  (let ((tokens (map match:substring (list-matches or-rx memory)))
        (enabled? #t))
    (apply + (map (lambda (match)
                    (cond ((string= "do()" match) (begin
                                                    (set! enabled? #t)
                                                    0))
                          ((string= "don't()" match) (begin
                                                       (set! enabled? #f)
                                                       0))
                          (else (if enabled?
                                    (mul match)
                                    0))))
                  tokens))))

(define (main)
  (let ((memory (file->str "input.txt")))
    (display "Part1: ")
    (display (part1 memory))
    (newline)
    (display "Part2: ")
    (display (part2 memory))
    (newline)))

(main)