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