From f0d18d31ced0227be78733ba2e1240aa1fa43a00 Mon Sep 17 00:00:00 2001 From: MsK` Date: Sat, 11 Dec 2021 10:49:04 +0100 Subject: [PATCH] customize default return value of matrix-get when peeking outside --- 09-smoke-basin/code.scm | 12 ++++++------ common.scm | 23 ++++++++++++++++------- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/09-smoke-basin/code.scm b/09-smoke-basin/code.scm index f791ab6..89e4f22 100644 --- a/09-smoke-basin/code.scm +++ b/09-smoke-basin/code.scm @@ -17,10 +17,10 @@ (lambda (y line) (vector-for-each (lambda (x altitude) - (let [(left (matrix-get heightmap (- x 1) y)) - (right (matrix-get heightmap (+ x 1) y)) - (up (matrix-get heightmap x (- y 1))) - (down (matrix-get heightmap x (+ y 1)))] + (let [(left (matrix-get heightmap (- x 1) y 9)) + (right (matrix-get heightmap (+ x 1) y 9)) + (up (matrix-get heightmap x (- y 1) 9)) + (down (matrix-get heightmap x (+ y 1) 9))] (when (and (< altitude left) (< altitude right) (< altitude up) @@ -49,7 +49,7 @@ (let [(ofs (offset x y))] (when (= (vector-ref visited ofs) 0) (vector-set! visited ofs 1) - (when (< (matrix-get heightmap x y) 9) + (when (< (matrix-get heightmap x y 9) 9) (closure x y) (when (> x 0) (flood-fill (- x 1) y)) (when (< x width-1) (flood-fill (+ x 1) y)) @@ -103,7 +103,7 @@ (let y-loop [(y 0)] (let x-loop [(x 0)] (let [(ofs (offset x y)) - (gray-level (* (matrix-get heightmap x y) 20))] + (gray-level (* (matrix-get heightmap x y 9) 20))] ; red channel (vector-set! data ofs gray-level) ; green channel diff --git a/common.scm b/common.scm index 32916a2..368c43b 100644 --- a/common.scm +++ b/common.scm @@ -13,19 +13,28 @@ (- (char->integer c) 48)) ; 48 is ASCII's number zero (define-record-type matrix (fields width height data)) -(define (matrix-get matrix x y) - (if (or (< x 0) - (< y 0) - (>= x (matrix-width matrix)) - (>= y (matrix-height matrix))) - 9 - (vector-ref (vector-ref (matrix-data matrix) y) x))) + (define (matrix-from-data data) (make-matrix (vector-length (vector-ref data 0)) (vector-length data) data)) +(define (matrix-get matrix x y default) + (if (or (< x 0) + (< y 0) + (>= x (matrix-width matrix)) + (>= y (matrix-height matrix))) + default + (vector-ref (vector-ref (matrix-data matrix) y) x))) + +(define (matrix-set! matrix x y value) + (when (and (>= x 0) + (>= y 0) + (< x (matrix-width matrix)) + (< y (matrix-height matrix))) + (vector-set! (vector-ref (matrix-data matrix) y) x value))) + ; parse 0-9 numerical data from file and return a matrix (define (load-matrix file) (let y-loop [(heightmap '())]