diff --git a/05-hydrothermal-venture/code.scm b/05-hydrothermal-venture/code.scm index 04ae979..d37761a 100644 --- a/05-hydrothermal-venture/code.scm +++ b/05-hydrothermal-venture/code.scm @@ -1,15 +1,6 @@ (import (srfi :43)) ; vector extensions (load "../common.scm") -; reads a numnber from input -; also consumes the next non-number character in the file! -(define (get-number file) - (let loop [(n 0)] - (let [(c (get-char file))] - (if (char-numeric? c) - [loop (+ (char->number c) (* n 10))] - n)))) - ; reads pairs of coordinates ; returns a list of the form (((x1 y1) (x2 y2))...) (define (read-lines file) diff --git a/11-dumbo-octopus/code.scm b/11-dumbo-octopus/code.scm index 1bfde15..a555ec5 100644 --- a/11-dumbo-octopus/code.scm +++ b/11-dumbo-octopus/code.scm @@ -22,7 +22,7 @@ (define (step! matrix) (let [(flashes '())] ; increase energy of all octopuses - (visit-matrix! + (update-matrix! matrix (lambda (x y energy) (when (= energy 9) @@ -35,7 +35,7 @@ (flash! matrix (vec2i-x (car flash)) (vec2i-y (car flash))))))) ; drain all octopuses that flashed - (visit-matrix! + (update-matrix! matrix (lambda (x y energy) (if (< energy 10) energy 0))) diff --git a/common.scm b/common.scm index 8b6e854..68b1c51 100644 --- a/common.scm +++ b/common.scm @@ -7,6 +7,21 @@ lines (loop (cons (get-line file) lines))))) +; reads a numnber from input +; also consumes the next non-number character in the file! +(define (get-number file) + (let [(sign 1)] + (let loop [(index 0) (n 0)] + (let [(c (get-char file))] + (cond + [(char-numeric? c) + (loop (+ index 1) (+ (char->number c) (* n 10)))] + [(and (char=? c #\-) + (= index 0)) + (set! sign -1) + (loop 1 n)] + [else (* sign n)]))))) + ; returns a list of numbers parsed from the first line of the file, ; separated by commas (define (read-comma-separated-numbers file) @@ -15,7 +30,7 @@ (cond [(char=? c #\,) (loop (cons n draws) 0)] [(char-whitespace? c) (reverse (cons n draws))] - [else (loop draws (+ (* n 10) (string->number (string c))))])))) + [else (loop draws (+ (* n 10) (char->number c)))])))) ; returns numbers 0 to 9 from ascii character (define (char->number c) @@ -31,6 +46,13 @@ (vector-length data) data)) +; returns a matrix object of given dimensions full of zeroes +(define (filled-matrix width height filler) + (matrix-from-data + (do [(i 0 (+ i 1)) + (v '() (cons (make-vector width filler) v))] + ((>= i height) (list->vector v)) '()))) + ; returns value at x,y coordinates in matrix ; if coordinate is out of bounds, returns default (define (matrix-get matrix x y default) @@ -74,7 +96,7 @@ ; matrix visitor ; calls function with all coordinates of matrix and value at corresponding point ; value returned by function is set at the visiting coordinate -(define (visit-matrix! matrix function) +(define (update-matrix! matrix function) (let [(data (matrix-data matrix)) (width-1 (- (matrix-width matrix) 1)) (height-1 (- (matrix-height matrix) 1))]