Compare commits

..

No commits in common. "689fb894ada8f3f05dd5299e27bd6096ae6fe7ba" and "8b638fcc187f9d3bf9d026ea9f339b6a62bbf3a1" have entirely different histories.

View File

@ -1,14 +1,12 @@
(local { : view } (require :fennel)) (local { : view } (require :fennel))
(local { : merge : any } (require :lume)) (local { : merge } (require :lume))
(fn wrap-longitude [x] (fn wrap-longitude [x]
(if (<= x -180) (wrap-longitude (+ x 360)) (if (<= x -180) (wrap-longitude (+ x 360))
(< 180 x) (wrap-longitude (- x 360)) (< 180 x) (wrap-longitude (- x 360))
x)) x))
(fn drive [{: x : y : direction : stopped &as r} distance] (fn drive [{: x : y : direction} distance]
(if stopped
r
(let [distance (let [distance
(if (. {:w true :e true} direction) (if (. {:w true :e true} direction)
(/ distance (math.cos (/ (* math.pi y) 180))) (/ distance (math.cos (/ (* math.pi y) 180)))
@ -17,7 +15,7 @@
:n {:y (+ y distance)} :n {:y (+ y distance)}
:s {:y (- y distance)} :s {:y (- y distance)}
:w {:x (wrap-longitude (- x distance))} :w {:x (wrap-longitude (- x distance))}
:e {:x (wrap-longitude (+ x distance))})))) :e {:x (wrap-longitude (+ x distance))})))
(fn turn-left [{: x : y : direction}] (fn turn-left [{: x : y : direction}]
(if (= y 90) (if (= y 90)
@ -43,22 +41,14 @@
} }
(. direction))})) (. direction))}))
(fn at-obstacle? [{: x : y : obstacles}]
(any obstacles
(fn [[ox oy]] (and (= ox x) (= oy y)))))
(fn command [rover string] (fn command [rover string]
(let [next-move
(merge rover (merge rover
(match string (match string
:f (drive rover 1) :f (drive rover 1)
:b (drive rover -1) :b (drive rover -1)
:r (turn-right rover) :r (turn-right rover)
:l (turn-left rover) :l (turn-left rover)
_ (assert false (. "unrecognised command " string))))] _ (assert false (. "unrecognised command " string)))))
(if (at-obstacle? next-move)
(merge rover {:stopped [next-move.x next-move.y]})
next-move)))
(fn fudge-for-pole [{: y &as r}] (fn fudge-for-pole [{: y &as r}]
(if (= y 90) (if (= y 90)
@ -72,11 +62,10 @@
_ c (ipairs cmds)] _ c (ipairs cmds)]
(merge rover (fudge-for-pole (command rover c))))) (merge rover (fudge-for-pole (command rover c)))))
(fn rover [x y direction ?obstacles] (fn rover [x y direction]
{: x {: x
: y : y
: direction : direction
:obstacles (or ?obstacles [])
}) })
;;;; TESTS ;;;; TESTS
@ -190,10 +179,9 @@
(execute (rover 0 89 :n) [:f :r]) (execute (rover 0 89 :n) [:f :r])
{:x 90 :y 90 :direction :s}) {:x 90 :y 90 :direction :s})
(expect "It does not move past obstacles" (expect "Near the North Pole, I can travel 90 degree in three steps"
(let [obstacles [[5 5] [7 5]]] (execute (rover 0 89 :n) [:f :r :f])
(execute (rover 5 3 :n obstacles) [:f :f :f :f :f :f])) {:x 90 :y 89 :direction :s})
{:x 5 :y 4 :direction :n :stopped [5 5]})
;; "TODO: deal with the south pole special casing" ;; "TODO: deal with the south pole special casing"