diff options
author | lamp | 2023-12-02 11:55:08 +0000 |
---|---|---|
committer | lamp | 2023-12-02 11:55:08 +0000 |
commit | a280deda223102a64e59c50a5adb7d4b700a07de (patch) | |
tree | f1e66686cceebcc5f1e65b679ddc88ce23aa2c28 /2.scm | |
parent | 61321d42aeaa471efca89a35c82b57ff71479972 (diff) |
add day 2 solutions
Diffstat (limited to '2.scm')
-rwxr-xr-x | 2.scm | 37 |
1 files changed, 37 insertions, 0 deletions
@@ -0,0 +1,37 @@ +#!/usr/bin/env -S guile -s +!# +(use-modules (ice-9 regex) + (ice-9 textual-ports) + (srfi srfi-1)) + +(define red-max 12) +(define green-max 13) +(define blue-max 14) + +(define (read-lines port) + (letrec ((loop (lambda (l ls) + (if (eof-object? l) + ls + (loop (get-line port) (cons l ls)))))) + (reverse (loop (get-line port) '())))) + +(define (valid-triplet? triplet) + (let* ((zero (string-match "(.)" "0")) + (red (string->number (match:substring (or (string-match "([0-9]+) red" triplet) zero) 1))) + (green (string->number (match:substring (or (string-match "([0-9]+) green" triplet) zero) 1))) + (blue (string->number (match:substring (or (string-match "([0-9]+) blue" triplet) zero) 1)))) + (and (<= red red-max) (<= green green-max) (<= blue blue-max)))) + +(define (line-value line) + (let* ((id-split (string-match "^Game ([0-9]+):(.*)$" line)) + (id (string->number (match:substring id-split 1))) + (rest (string-split (match:substring id-split 2) #\;)) + (valid? (fold (lambda (x y) (and x y)) #t (map valid-triplet? rest)))) + (if valid? id 0))) + +(line-value "Game 38: 2 blue, 4 green, 11 red; 7 green, 6 red, 2 blue; 1 green, 3 red, 1 blue; 4 blue, 4 green, 4 red; 2 red, 5 blue, 2 green") + +(let* ((port (open-input-file "2.txt")) + (lines (read-lines port))) + (close-port port) + (display (fold + 0 (map line-value lines)))) |