summaryrefslogtreecommitdiff
path: root/perfectly-spherical-houses-in-a-vacuum/pshiav.scm
diff options
context:
space:
mode:
Diffstat (limited to 'perfectly-spherical-houses-in-a-vacuum/pshiav.scm')
-rw-r--r--perfectly-spherical-houses-in-a-vacuum/pshiav.scm54
1 files changed, 54 insertions, 0 deletions
diff --git a/perfectly-spherical-houses-in-a-vacuum/pshiav.scm b/perfectly-spherical-houses-in-a-vacuum/pshiav.scm
new file mode 100644
index 0000000..d117cce
--- /dev/null
+++ b/perfectly-spherical-houses-in-a-vacuum/pshiav.scm
@@ -0,0 +1,54 @@
+(define-module (pshiav)
+ #:use-module (srfi srfi-1)
+ #:export (pshiav
+ add-coordinates
+ direction->pair))
+
+(define (pshiav str num)
+ "Given string of cardinal directions STR,
+calculates the number of visited places on
+a grid.
+
+NUM specifies the number of visitors. Will
+always be at least one."
+ (set! num (max num 1))
+ (let ((visitors (map (lambda (x)
+ (add-coordinates))
+ (iota num))))
+ (let loop ((i 0) (lst (map direction->pair
+ (string->list str))))
+ (if (null? lst)
+ (length (delete-duplicates
+ (apply append (map (lambda (visitor)
+ (visitor '(0 . 0)))
+ visitors))))
+ (begin
+ ((list-ref visitors i) (car lst))
+ (loop (modulo (1+ i) (length visitors))
+ (cdr lst)))))))
+
+(define (add-coordinates)
+ (let ((hist '((0 . 0))))
+ (lambda dir
+ "Given cons pair DIR, increments the previous
+position, and returns HIST, a history of visited
+positions."
+ (set! hist (cons
+ (cons (+ (caar dir)
+ (caar hist))
+ (+ (cdar dir)
+ (cdar hist)))
+ hist))
+ hist)))
+
+
+(define (direction->pair char)
+ "Given a character representing one of the four
+cardinal directions, return a pair representing
+a change in coordinates."
+ (cond
+ ((char=? char #\^) '(0 . 1))
+ ((char=? char #\>) '(1 . 0))
+ ((char=? char #\v) '(0 . -1))
+ ((char=? char #\<) '(-1 . 0))
+ (#t '(0 . 0))))