summary refs log tree commit diff stats
path: root/day2.scm
blob: bb6571f40d3f20e58de71883dcc74879f7e7e9af (plain) (blame)
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
53
#!/usr/bin/env gosh
(use file.util)

(define (read-input filename)
  (map string->number (string-split (file->string filename) ",")))

(define (run-opcode vec pos)
  (let ((opcode (vector-ref vec pos)))
    (cond
      ((= opcode 1)
        (vector-set! 
          vec
          (vector-ref vec (+ pos 3)) 
          (+ (vector-ref vec (vector-ref vec (+ pos 1))) 
             (vector-ref vec (vector-ref vec (+ pos 2)))))
        (run-opcode vec (+ pos 4)))
      ((= opcode 2)
        (vector-set! 
          vec 
          (vector-ref vec (+ pos 3))
          (* (vector-ref vec (vector-ref vec (+ pos 1))) 
             (vector-ref vec (vector-ref vec (+ pos 2)))))
        (run-opcode vec (+ pos 4)))
      ((= opcode 99) vec))))

(define (run-program input noun verb)
  (let ((input-vector (list->vector input)))
    (vector-set! input-vector 1 noun)
    (vector-set! input-vector 2 verb)
    (vector-ref (run-opcode input-vector 0) 0)))

(define (part1 input)
  (run-program input 12 2))

(define cartesian-product (lambda (xs ys)
 (if (or (zero? (length xs)) (zero? (length ys)))
     '()
     (fold append '() (map (lambda (x) (map (lambda (y) (cons x y)) ys)) xs)))))

(define (part2 input)
  (letrec ((nouns (iota 100))
           (verbs (iota 100))
           (output (find 
                    (lambda (x) 
                      (= 19690720 
                        (run-program input (car x) (cdr x))))
                    (cartesian-product nouns verbs))))
    (+ (cdr output) (* 100 (car output)))))

(define (main args)
  (let ((input (read-input "inputs/day2.txt")))
    (print (part1 input))
    (print (part2 input))))