aboutsummaryrefslogtreecommitdiff
path: root/2024/aoc-utils.scm
diff options
context:
space:
mode:
Diffstat (limited to '2024/aoc-utils.scm')
-rw-r--r--2024/aoc-utils.scm48
1 files changed, 47 insertions, 1 deletions
diff --git a/2024/aoc-utils.scm b/2024/aoc-utils.scm
index ed16bfd..9f22c47 100644
--- a/2024/aoc-utils.scm
+++ b/2024/aoc-utils.scm
@@ -1,12 +1,25 @@
(define-module (aoc-utils)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-9)
+ #:use-module (srfi srfi-9 gnu)
#:use-module (ice-9 regex)
#:use-module (ice-9 rdelim)
#:export (file->list
file->str
file->matrix
- lines->number-list))
+ lines->number-list
+
+ <matrix>
+ matrix
+ make-matrix
+ matrix-inner
+ matrix-width
+ matrix-height
+ matrix-ref
+ matrix-valid-x?
+ matrix-valid-y?
+ matrix-valid-point?
+ list-flatten))
(define (file->list filename)
(let ((lines (string-split (call-with-input-file filename read-string) #\Newline)))
@@ -35,3 +48,36 @@
((< i 0))
(set! retval (cons i retval)))
retval))
+
+;; Matrix utilities
+
+(define-record-type <matrix>
+ (matrix inner width height)
+ matrix?
+ (inner matrix-inner)
+ (width matrix-width)
+ (height matrix-height))
+
+(define (make-matrix lst)
+ (let ((height (length lst))
+ (width (length (car lst))))
+ (matrix (list-flatten lst) width height)))
+
+(define (list-flatten lst)
+ (apply append lst))
+
+(define (matrix-ref matrix x y)
+ (if (matrix-valid-point? matrix x y)
+ (list-ref (matrix-inner matrix)
+ (+ x (* y (matrix-height matrix))))
+ #f))
+
+(define (matrix-valid-x? matrix x)
+ (and (>= x 0) (< x (matrix-width matrix))))
+
+(define (matrix-valid-y? matrix y)
+ (and (>= y 0) (< y (matrix-height matrix))))
+
+(define (matrix-valid-point? matrix x y)
+ (and (matrix-valid-x? matrix x)
+ (matrix-valid-y? matrix y)))