Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Created August 1, 2022 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericnormand/d6fa214ed0733998a2e0a3f4d3fb62e5 to your computer and use it in GitHub Desktop.
Save ericnormand/d6fa214ed0733998a2e0a3f4d3fb62e5 to your computer and use it in GitHub Desktop.
472 Eric Normand Newsletter

Roboto

A futuristic robot is programmed to take in a sequence of numbers. Each number is the distance to travel in a cardinal direction (north, south, east, west). It starts facing north at (0, 0), travels straight ahead by the distance given in the first number, then turns 90 degrees clockwise, now facing east. Then it repeats with the next number. Your job is to calculate where it ends up at the end of the sequence.

Examples

(move []) ;=> [0 0] ;; No motion
(move [10]) ;=> [0 10] ;; move 10 straight north
(move [10 2]) ;=> [2 10]
(move [10 2 3]) ;=> [2 7]

Thanks to this site for the problem idea, where it is rated Very Hard in Ruby. The problem has been modified.

Please submit your solutions as comments on this gist.

To subscribe: https://ericnormand.me/newsletter

@cmaus00
Copy link

cmaus00 commented Aug 7, 2022

(defn move [steps]
  (let [directions (cycle [[0 1] [1 0] [0 -1] [-1 0]])
        vecmult (fn [v s] (map #(* s %) v))
        vecadd (fn [& vs] (apply map + vs))]
    (->> steps
         (map vector directions)
         (map #(apply vecmult %))
         (reduce vecadd [0 0]))))

@ericnormand
Copy link
Author

map-reduce has been on my mind.

(def directions
  [[0 1]  ;; north
   [1 0]  ;; east
   [0 -1] ;; south
   [-1 0] ;; west
   ])

(defn vec+ [a b]
  (mapv + a b))

(defn vec-scalar* [v s]
  (mapv #(* s %) v))

(defn move [xs]
  (reduce vec+
          [0 0]
          (map vec-scalar* (cycle directions) xs)))

@barrosfelipe
Copy link

Bit late to this party but here is mine:

(defn move [xs]
  (if-not (seq xs)
    [0 0]
    (->> xs
         (partition 4 4 [0 0 0 0])
         (apply #(map + %))
         ((fn [[a b c d]] [(- b d) (- a c)])))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment