refactoring (probably needed for previous days too, oops)

This commit is contained in:
2021-12-21 23:46:46 +01:00
parent 089f2c8800
commit aa77b51cd0
3 changed files with 26 additions and 13 deletions

View File

@@ -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)

View File

@@ -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)))

View File

@@ -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))]