commit 64c9fd7b88b8465ce1a84c4f8fead01b467739ff
parent 4b1f2ee9238bd561ab3d67ef2095078901dbf2c1
Author: Daniel Barlow <dan@telent.net>
Date: Sun, 22 Jan 2023 22:05:14 +0000
handle north pole
Diffstat:
| M | rover.fnl | | | 75 | ++++++++++++++++++++++++++++++++++++++++++++++++--------------------------- |
1 file changed, 48 insertions(+), 27 deletions(-)
diff --git a/rover.fnl b/rover.fnl
@@ -29,39 +29,50 @@
:w {:x (wrap-longitude (- x distance))}
:e {:x (wrap-longitude (+ x distance))})))
-(fn turn-left [direction]
- {:direction
- (-> {
- :n :w
- :w :s
- :s :e
- :e :n
- }
- (. direction))})
-
-(fn turn-right [direction]
- {:direction
- (-> {
- :n :e
- :e :s
- :s :w
- :w :n
- }
- (. direction))})
+(fn turn-left [{: x : y : direction}]
+ (if (= y 90)
+ {:x (wrap-longitude (- x 90))}
+ {:direction
+ (-> {
+ :n :w
+ :w :s
+ :s :e
+ :e :n
+ }
+ (. direction))}))
+
+(fn turn-right [{: x : y : direction}]
+ (if (= y 90)
+ {:x (wrap-longitude (+ x 90))}
+ {:direction
+ (-> {
+ :n :e
+ :e :s
+ :s :w
+ :w :n
+ }
+ (. direction))}))
(fn command [rover string]
(merge rover
(match string
:f (drive rover 1)
:b (drive rover -1)
- :r (turn-right rover.direction)
- :l (turn-left rover.direction)
+ :r (turn-right rover)
+ :l (turn-left rover)
_ (assert false (. "unrecognised command " string)))))
+(fn fudge-for-pole [{: y &as r}]
+ (if (= y 90)
+ (merge r {:direction :s})
+ (= y -90)
+ (merge r {:direction :n})
+ r))
+
(fn execute [rover cmds]
(accumulate [rover rover
_ c (ipairs cmds)]
- (merge rover (command rover c))))
+ (merge rover (fudge-for-pole (command rover c)))))
(fn rover [x y direction]
{: x
@@ -155,10 +166,20 @@
(execute (rover 179 0 :e) [:f :f :f])
{:x -178 :y 0 :direction :e})
-"if we travel west past x=-180, x becomes positive 180"
-"if we travel east past x=180, x becomes -180"
-"if we travel east/west at a non-zero latitude, we don't move a full unit"
-"if we arrive at the north pole, we are {:y 90 :direction :s}"
-"if we arrive at the north pole and turn 90 degrees left, x = x - 90"
+(expect "At the North Pole we always point south"
+ (execute (rover 0 89 :n) [:f])
+ {:x 0 :y 90 :direction :s})
+
+(expect "At the North Pole, turning left affects x not direction"
+ (execute (rover 0 89 :n) [:f :l])
+ {:x -90 :y 90 :direction :s})
+
+(expect "At the North Pole, turning right affects x not direction"
+ (execute (rover 0 89 :n) [:f :r])
+ {:x 90 :y 90 :direction :s})
+
+(expect "Near the North Pole, I can travel 90 degree in three steps"
+ (execute (rover 0 89 :n) [:f :r :f])
+ {:x 90 :y 89 :direction :s})
(print "OK")